Jump to content

Synchsafe: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Yobot (talk | contribs)
m WP:CHECKWIKI error fixes using AWB (9475)
Venge (talk | contribs)
m C/C++ code: use of unassigned variable; Pascal: while case-insensitive, good practice should still be followed
Line 19: Line 19:
int synchsafe(int in)
int synchsafe(int in)
{
{
int out, mask = 0x7F;
int out = 0, mask = 0x7F;


while (mask ^ 0x7FFFFFFF) {
while (mask ^ 0x7FFFFFFF) {
Line 63: Line 63:
IsOK := false;
IsOK := false;


while ( isOK ) DO
while ( IsOK ) DO
begin
begin
ret := (input and (not mask));
ret := (input and (not mask));

Revision as of 06:51, 6 October 2014

Synchsafe integers appear in ID3 tags that are attached to an MP3 file.

An ID3 tag[1] encodes several blocks of data. Some blocks (containing metadata about the content of the file) are variable in length and are encoded as 'synchsafe' integers to distinguish them from data in other blocks.

In a synchsafe integer, the most significant bit of each byte is zero, making seven bits out of eight available. So, for example, a 32-bit synchsafe integer can only store 28 bits of information.

Examples:

(%11111111) is encoded as a 16-bit synchsafe integer (%00000001 01111111).
(%11111111 11111111) is encoded as a 24-bit synchsafe integer (%00000011 01111111 01111111).

The ID3 specifications require that multibyte numbers such as these be stored in big-endian order,[1] so the bytes will be ordered exactly as laid out in the examples above.

C/C++ code to decode Synchsafe encoded values

int synchsafe(int in)
{
	int out = 0, mask = 0x7F;

	while (mask ^ 0x7FFFFFFF) {
		out = in & ~mask;
		out <<= 1;
		out |= in & mask;
		mask = ((mask + 1) << 8) - 1;
		in = out;
	}

	return out;
}

int unsynchsafe(int in)
{
	int out = 0, mask = 0x7F000000;

	while (mask) {
		out >>= 1;
		out |= in & mask;
		mask >>= 8;
	}

	return out;
}

Pascal code to decode Synchsafe encoded values

function synchsafe(input: integer):integer;
var
  ret: integer;
  mask: integer;
  IsOK: boolean;
begin
  //by mp3mango.com 
  mask := $7F;

  if (mask XOR $7FFFFFFF) > 0 then
    IsOK := true
  else
    IsOK := false;

  while ( IsOK ) DO
  begin
    ret := (input and (not mask));
    ret := (ret shl 1);
    ret := ret or (input and mask);
    mask := ((mask + 1) shl 8) - 1;
    input := ret;

    if (mask XOR $7FFFFFFF) > 0 then
      IsOK := true
    else
      IsOK := false;
  end;

  result := ret;
end;

function unsynchsafe(input: integer):integer;
var
  ret: integer;
  mask: integer;
begin
  ret := 0;
  mask := $7F000000;

  while (mask <> 0) do
  begin
    ret := ret shr 1;
    ret := ret or (input and mask);
    mask := mask shr 8;
  end;

  result := ret;

end;

References

  1. ^ a b "ID3 tag version 2.4.0 - Structure".