Example #1
0
BOOL NETuint16_t(uint16_t *ip)
{
	uint16_t *store = (uint16_t *) &NetMsg.body[NetMsg.size];

	// Make sure there is enough data/space left in the packet
	if (sizeof(uint16_t) + NetMsg.size > sizeof(NetMsg.body) || !NetMsg.status)
	{
		return NetMsg.status = false;
	}

	// Convert the integer into the network byte order (big endian)
	if (NETgetPacketDir() == PACKET_ENCODE)
	{
		*store = SDL_SwapBE16(*ip);
	}
	else if (NETgetPacketDir() == PACKET_DECODE)
	{
		*ip = SDL_SwapBE16(*store);
	}

	// Increment the size of the message
	NetMsg.size += sizeof(uint16_t);

	return true;
}
Example #2
0
static boolean ReadFileHeader(midi_file_t *file, FILE *stream)
{
    size_t records_read;
    unsigned int format_type;

    records_read = fread(&file->header, sizeof(midi_header_t), 1, stream);

    if (records_read < 1)
    {
        return false;
    }

    if (!CheckChunkHeader(&file->header.chunk_header, HEADER_CHUNK_ID)
     || SDL_SwapBE32(file->header.chunk_header.chunk_size) != 6)
    {
        fprintf(stderr, "ReadFileHeader: Invalid MIDI chunk header! "
                        "chunk_size=%i\n",
                        SDL_SwapBE32(file->header.chunk_header.chunk_size));
        return false;
    }

    format_type = SDL_SwapBE16(file->header.format_type);
    file->num_tracks = SDL_SwapBE16(file->header.num_tracks);

    if ((format_type != 0 && format_type != 1)
     || file->num_tracks < 1)
    {
        fprintf(stderr, "ReadFileHeader: Only type 0/1 "
                                         "MIDI files supported!\n");
        return false;
    }

    return true;
}
Example #3
0
Uint16 SDL_ReadBE16 (SDL_RWops *src)
{
    Uint16 value;

    SDL_RWread(src, &value, (sizeof value), 1);
    return(SDL_SwapBE16(value));
}
Example #4
0
/* Resolve a host name and port to an IP address in network form */
int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port)
{
	int retval = 0;

	/* Perform the actual host resolution */
	if ( host == NULL ) {
		address->host = INADDR_ANY;
	} else {
		address->host = inet_addr(host);
		if ( address->host == INADDR_NONE ) {
			struct hostent *hp;

			hp = gethostbyname(host);
			if ( hp ) {
				memcpy(&address->host,hp->h_addr,hp->h_length);
			} else {
				retval = -1;
			}
		}
	}
	address->port = SDL_SwapBE16(port);

	/* Return the status */
	return(retval);
}
Example #5
0
Uint16
SDL_ReadBE16(SDL_RWops * src)
{
    Uint16 value = 0;

    SDL_RWread(src, &value, sizeof (value), 1);
    return SDL_SwapBE16(value);
}
Example #6
0
unsigned int MIDI_GetFileTimeDivision(midi_file_t *file)
{
    short result = SDL_SwapBE16(file->header.time_division);

    // Negative time division indicates SMPTE time and must be handled
    // differently.
    if (result < 0)
        return (signed int)(-result / 256) * (signed int)(result & 0xFF);
    else
        return result;
}
Example #7
0
static void conv_mix_buf_u16msb_stereo(void *userdata, Uint8 *_stream, int len)
{
    register Uint32 i;
    register Uint16 *stream = (Uint16 *) _stream;
    register Uint16 val;
    register Uint32 max = len / 2;
    for (i = 0; i < max; i++)
    {
        val = (Uint16) ((mixbuf[i] * 32767.0f) + 32768.0f);
        *stream = SDL_SwapBE16(val);
        stream++;
    } /* for */
} /* conv_mix_buf_s16_msb_stereo */
Example #8
0
static void conv_mix_buf_s16_msb_mono(void *userdata, Uint8 *_stream, int len)
{
    register Uint32 i;
    register Sint16 *stream = (Sint16 *) _stream;
    register Sint16 val;
    register Uint32 max = len / 2;
    for (i = 0; i < max; i += 2)
    {
        val = (Sint16) (((mixbuf[i] + mixbuf[i+1]) * 0.5f) * 32767.0f);
        *stream = SDL_SwapBE16(val);
        stream++;
    } /* for */
} /* conv_mix_buf_s16_msb_mono */
Example #9
0
// Read and check the header chunk.
static dboolean ReadFileHeader(midi_file_t *file, FILE *stream)
{
    size_t              records_read;
    unsigned int        format_type;

    records_read = fread(&file->header, sizeof(midi_header_t), 1, stream);

    if (records_read < 1)
        return false;

    if (!CheckChunkHeader(&file->header.chunk_header, HEADER_CHUNK_ID)
        || SDL_SwapBE32(file->header.chunk_header.chunk_size) != 6)
        return false;

    format_type = SDL_SwapBE16(file->header.format_type);
    file->num_tracks = SDL_SwapBE16(file->header.num_tracks);

    if ((format_type != 0 && format_type != 1) || file->num_tracks < 1)
        return false;

    return true;
}
Example #10
0
/* Open a UDP network socket
   If 'port' is non-zero, the UDP socket is bound to a fixed local port.
*/
extern UDPsocket SDLNet_UDP_Open(u16 port)
{
	UDPsocket sock;

	/* Allocate a UDP socket structure */
	sock = (UDPsocket)malloc(sizeof(*sock));
	if ( sock == NULL ) {
		iprintf("SDL_NET: Out of memory\n");
		goto error_return;
	}
	memset(sock, 0, sizeof(*sock));
	
	/* Open the socket */
	sock->channel = socket(AF_INET, SOCK_DGRAM, 0);

	if ( sock->channel == INVALID_SOCKET ) 
	{
		iprintf("SDL_NET: Couldn't create socket\n");
		goto error_return;
	}

	/* Bind locally, if appropriate */
	if ( port )
	{
		struct sockaddr_in sock_addr;
		memset(&sock_addr, 0, sizeof(sock_addr));
		sock_addr.sin_family = AF_INET;
		sock_addr.sin_addr.s_addr = INADDR_ANY;
		sock_addr.sin_port = SDL_SwapBE16(port);
	//	sock_addr.sin_port = port;

		/* Bind the socket for listening */
		if ( bind(sock->channel, (struct sockaddr *)&sock_addr,
				sizeof(sock_addr)) == SOCKET_ERROR ) {
			iprintf("SDL_NET: Couldn't bind to local port\n");
			goto error_return;
		}
		/* Fill in the channel host address */
		sock->address.host = sock_addr.sin_addr.s_addr;
		sock->address.port = sock_addr.sin_port;
	}

	/* The socket is ready */
	
	return(sock);

error_return:
	SDLNet_UDP_Close(sock);
	
	return(NULL);
}
Example #11
0
/* Resolve a host name and port to an IP address in network form */
int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port)
{
	int retval = 0;

	/* Perform the actual host resolution */
	if ( host == NULL ) {
		address->host = INADDR_ANY;
	} else {
/*		int a[4];

		address->host = INADDR_NONE;
		
		if ( sscanf(host, "%d.%d.%d.%d", a, a+1, a+2, a+3) == 4 ) {
			if ( !(a[0] & 0xFFFFFF00) && !(a[1] & 0xFFFFFF00) &&
			     !(a[2] & 0xFFFFFF00) && !(a[3] & 0xFFFFFF00) ) {
				address->host = ((a[0] << 24) |
				                 (a[1] << 16) |
				                 (a[2] <<  8) | a[3]);
				if ( address->host == 0x7F000001 ) {
					address->host = OTlocalhost;
				}
			}
		}
		
		if ( address->host == INADDR_NONE ) {*/
			InetHostInfo hinfo;
			
			/* Check for special case - localhost */
			if ( strcmp(host, "localhost") == 0 )
				return(SDLNet_ResolveHost(address, "127.0.0.1", port));

			/* Have OpenTransport resolve the hostname for us */
			retval = OTInetStringToAddress(dnsStatus.dns, (char *)host, &hinfo);
			if (retval == noErr) {
				while( dnsStatus.stat != dnsResolved )
					{WaitNextEvent(everyEvent, 0, 1, NULL );}
				address->host = hinfo.addrs[0];
			}
		//}
	}
	
	address->port = SDL_SwapBE16(port);

	/* Return the status */
	return(retval);
}
// Most of this function by ZZZ.
// Incoming port number should be in network byte order.
OSErr NetDDPOpenSocket(short *ioPortNumber, PacketHandlerProcPtr packetHandler)
{
//fdprintf("NetDDPOpenSocket\n");
	assert(packetHandler);

	// Allocate packet buffer (this is Christian's part)
	assert(!sUDPPacketBuffer);
	sUDPPacketBuffer = SDLNet_AllocPacket(ddpMaxData);
	if (sUDPPacketBuffer == NULL)
		return -1;

        //PORTGUESS
	// Open socket (SDLNet_Open seems to like port in host byte order)
        // NOTE: only SDLNet_UDP_Open wants port in host byte order.  All other uses of port in SDL_net
        // are in network byte order.
	sSocket = SDLNet_UDP_Open(SDL_SwapBE16(*ioPortNumber));
	if (sSocket == NULL) {
		SDLNet_FreePacket(sUDPPacketBuffer);
		sUDPPacketBuffer = NULL;
		return -1;
	}

        // Set up socket set
        sSocketSet = SDLNet_AllocSocketSet(1);
        SDLNet_UDP_AddSocket(sSocketSet, sSocket);
        
        // Set up receiver
        sKeepListening		= true;
        sPacketHandler		= packetHandler;
        sReceivingThread	= SDL_CreateThread(receive_thread_function, "NetDDPOpenSocket_ReceivingThread", NULL);

        // Set receiving thread priority very high
        bool	theResult = BoostThreadPriority(sReceivingThread);
        if(theResult == false)
            fdprintf("warning: BoostThreadPriority() failed; network performance may suffer\n");
        
        //PORTGUESS but we should generally keep port in network order, I think?
	// We really ought to return the "real" port we bound to in *ioPortNumber...
	// for now we just hand back whatever they handed us.
	//*ioPortNumber = *ioPortNumber;
	return 0;
}
Example #13
0
void MessageOut::write2(Uint16 value){
	expandData((this->pos) + 2);
	Uint16 tmp = SDL_SwapBE16(value);
	memcpy((this->myData)+(this->pos), &tmp, 2);
    this->pos += 2;
}
Example #14
0
SDL_Surface *IMG_LoadLBM_RW( SDL_RWops *src )
{
	int start;
	SDL_Surface *Image;
	Uint8       id[4], pbm, colormap[MAXCOLORS*3], *MiniBuf, *ptr, count, color, msk;
	Uint32      size, bytesloaded, nbcolors;
	Uint32      i, j, bytesperline, nbplanes, stencil, plane, h;
	Uint32      remainingbytes;
	Uint32      width;
	BMHD	      bmhd;
	char        *error;
	Uint8       flagHAM,flagEHB;

	Image   = NULL;
	error   = NULL;
	MiniBuf = NULL;

	if ( !src ) {
		/* The error message has been set in SDL_RWFromFile */
		return NULL;
	}
	start = SDL_RWtell(src);

	if ( !SDL_RWread( src, id, 4, 1 ) )
	{
		error="error reading IFF chunk";
		goto done;
	}

	/* Should be the size of the file minus 4+4 ( 'FORM'+size ) */
	if ( !SDL_RWread( src, &size, 4, 1 ) )
	{
		error="error reading IFF chunk size";
		goto done;
	}

	/* As size is not used here, no need to swap it */

	if ( memcmp( id, "FORM", 4 ) != 0 )
	{
		error="not a IFF file";
		goto done;
	}

	if ( !SDL_RWread( src, id, 4, 1 ) )
	{
		error="error reading IFF chunk";
		goto done;
	}

	pbm = 0;

	/* File format : PBM=Packed Bitmap, ILBM=Interleaved Bitmap */
	if ( !memcmp( id, "PBM ", 4 ) ) pbm = 1;
	else if ( memcmp( id, "ILBM", 4 ) )
	{
		error="not a IFF picture";
		goto done;
	}

	nbcolors = 0;

	memset( &bmhd, 0, sizeof( BMHD ) );
	flagHAM = 0;
	flagEHB = 0;

	while ( memcmp( id, "BODY", 4 ) != 0 )
	{
		if ( !SDL_RWread( src, id, 4, 1 ) ) 
		{
			error="error reading IFF chunk";
			goto done;
		}

		if ( !SDL_RWread( src, &size, 4, 1 ) )
		{
			error="error reading IFF chunk size";
			goto done;
		}

		bytesloaded = 0;

		size = SDL_SwapBE32( size );

		if ( !memcmp( id, "BMHD", 4 ) ) /* Bitmap header */
		{
			if ( !SDL_RWread( src, &bmhd, sizeof( BMHD ), 1 ) )
			{
				error="error reading BMHD chunk";
				goto done;
			}

			bytesloaded = sizeof( BMHD );

			bmhd.w 		= SDL_SwapBE16( bmhd.w );
			bmhd.h 		= SDL_SwapBE16( bmhd.h );
			bmhd.x 		= SDL_SwapBE16( bmhd.x );
			bmhd.y 		= SDL_SwapBE16( bmhd.y );
			bmhd.tcolor = SDL_SwapBE16( bmhd.tcolor );
			bmhd.Lpage 	= SDL_SwapBE16( bmhd.Lpage );
			bmhd.Hpage 	= SDL_SwapBE16( bmhd.Hpage );
		}

		if ( !memcmp( id, "CMAP", 4 ) ) /* palette ( Color Map ) */
		{
			if ( !SDL_RWread( src, &colormap, size, 1 ) )
			{
				error="error reading CMAP chunk";
				goto done;
			}

			bytesloaded = size;
			nbcolors = size / 3;
		}

		if ( !memcmp( id, "CAMG", 4 ) ) /* Amiga ViewMode  */
		{
			Uint32 viewmodes;
			if ( !SDL_RWread( src, &viewmodes, sizeof(viewmodes), 1 ) )
			{
				error="error reading CAMG chunk";
				goto done;
			}

			bytesloaded = size;
			viewmodes = SDL_SwapBE32( viewmodes );
			if ( viewmodes & 0x0800 )
				flagHAM = 1;
			if ( viewmodes & 0x0080 )
				flagEHB = 1;
		}

		if ( memcmp( id, "BODY", 4 ) )
		{
			if ( size & 1 )	++size;  	/* padding ! */
			size -= bytesloaded;
			/* skip the remaining bytes of this chunk */
			if ( size )	SDL_RWseek( src, size, RW_SEEK_CUR );
		}
	}

	/* compute some usefull values, based on the bitmap header */

	width = ( bmhd.w + 15 ) & 0xFFFFFFF0;  /* Width in pixels modulo 16 */

	bytesperline = ( ( bmhd.w + 15 ) / 16 ) * 2;

	nbplanes = bmhd.planes;

	if ( pbm )                         /* File format : 'Packed Bitmap' */
	{
		bytesperline *= 8;
		nbplanes = 1;
	}

	stencil = (bmhd.mask & 1);   /* There is a mask ( 'stencil' ) */

	/* Allocate memory for a temporary buffer ( used for
           decompression/deinterleaving ) */

	MiniBuf = (void *)malloc( bytesperline * (nbplanes + stencil) );
	if ( MiniBuf == NULL )
	{
		error="no enough memory for temporary buffer";
		goto done;
	}

	if ( ( Image = SDL_CreateRGBSurface( SDL_SWSURFACE, width, bmhd.h, (bmhd.planes==24 || flagHAM==1)?24:8, 0, 0, 0, 0 ) ) == NULL )
	   goto done;

	if ( bmhd.mask & 2 )               /* There is a transparent color */
		SDL_SetColorKey( Image, SDL_SRCCOLORKEY, bmhd.tcolor );

	/* Update palette informations */

	/* There is no palette in 24 bits ILBM file */
	if ( nbcolors>0 && flagHAM==0 )
	{
		/* FIXME: Should this include the stencil? See comment below */
		int nbrcolorsfinal = 1 << (nbplanes + stencil);
		ptr = &colormap[0];

		for ( i=0; i<nbcolors; i++ )
		{
			Image->format->palette->colors[i].r = *ptr++;
			Image->format->palette->colors[i].g = *ptr++;
			Image->format->palette->colors[i].b = *ptr++;
		}

		/* Amiga EHB mode (Extra-Half-Bright) */
		/* 6 bitplanes mode with a 32 colors palette */
		/* The 32 last colors are the same but divided by 2 */
		/* Some Amiga pictures save 64 colors with 32 last wrong colors, */
		/* they shouldn't !, and here we overwrite these 32 bad colors. */
		if ( (nbcolors==32 || flagEHB ) && (1<<bmhd.planes)==64 )
		{
			nbcolors = 64;
			ptr = &colormap[0];
			for ( i=32; i<64; i++ )
			{
				Image->format->palette->colors[i].r = (*ptr++)/2;
				Image->format->palette->colors[i].g = (*ptr++)/2;
				Image->format->palette->colors[i].b = (*ptr++)/2;
			}
		}

		/* If nbcolors < 2^nbplanes, repeat the colormap */
		/* This happens when pictures have a stencil mask */
		if ( nbrcolorsfinal > (1<<bmhd.planes) ) {
			nbrcolorsfinal = (1<<bmhd.planes);
		}
		for ( i=nbcolors; i < (Uint32)nbrcolorsfinal; i++ )
		{
			Image->format->palette->colors[i].r = Image->format->palette->colors[i%nbcolors].r;
			Image->format->palette->colors[i].g = Image->format->palette->colors[i%nbcolors].g;
			Image->format->palette->colors[i].b = Image->format->palette->colors[i%nbcolors].b;
		}
		if ( !pbm )
			Image->format->palette->ncolors = nbrcolorsfinal;
	}

	/* Get the bitmap */

	for ( h=0; h < bmhd.h; h++ )
	{
		/* uncompress the datas of each planes */

		for ( plane=0; plane < (nbplanes+stencil); plane++ )
		{
			ptr = MiniBuf + ( plane * bytesperline );

			remainingbytes = bytesperline;

			if ( bmhd.tcomp == 1 )	    /* Datas are compressed */
			{
				do
				{
					if ( !SDL_RWread( src, &count, 1, 1 ) )
					{
						error="error reading BODY chunk";
						goto done;
					}

					if ( count & 0x80 )
					{
						count ^= 0xFF;
						count += 2; /* now it */

						if ( ( count > remainingbytes ) || !SDL_RWread( src, &color, 1, 1 ) )
						{
							error="error reading BODY chunk";
							goto done;
						}
						memset( ptr, color, count );
					}
					else
					{
						++count;

						if ( ( count > remainingbytes ) || !SDL_RWread( src, ptr, count, 1 ) )
						{
						   error="error reading BODY chunk";
							goto done;
						}
					}

					ptr += count;
					remainingbytes -= count;

				} while ( remainingbytes > 0 );
			}
			else
			{
				if ( !SDL_RWread( src, ptr, bytesperline, 1 ) )
				{
					error="error reading BODY chunk";
					goto done;
				}
			}
		}

		/* One line has been read, store it ! */

		ptr = Image->pixels;
		if ( nbplanes==24 || flagHAM==1 )
			ptr += h * width * 3;
		else
			ptr += h * width;

		if ( pbm )                 /* File format : 'Packed Bitmap' */
		{
		   memcpy( ptr, MiniBuf, width );
		}
		else		/* We have to un-interlace the bits ! */
		{
			if ( nbplanes!=24 && flagHAM==0 )
			{
				size = ( width + 7 ) / 8;

				for ( i=0; i < size; i++ )
				{
					memset( ptr, 0, 8 );

					for ( plane=0; plane < (nbplanes + stencil); plane++ )
					{
						color = *( MiniBuf + i + ( plane * bytesperline ) );
						msk = 0x80;

						for ( j=0; j<8; j++ )
						{
							if ( ( plane + j ) <= 7 ) ptr[j] |= (Uint8)( color & msk ) >> ( 7 - plane - j );
							else 	                    ptr[j] |= (Uint8)( color & msk ) << ( plane + j - 7 );

							msk >>= 1;
						}
					}
					ptr += 8;
				}
			}
			else
			{
Example #15
0
		uint16_t big16(uint16_t number)
		{
			return SDL_SwapBE16(number);
		}
Example #16
0
Uint16 SDLNet_Read16(void *areap)
{
	return (SDL_SwapBE16(*(Uint16 *)(areap)));
}
Example #17
0
/* Open a UDP network socket
   If 'port' is non-zero, the UDP socket is bound to a fixed local port.
*/
extern UDPsocket SDLNet_UDP_Open(Uint16 port)
{
	UDPsocket sock;
#ifdef MACOS_OPENTRANSPORT
	EndpointRef dummy = NULL;
#endif

	/* Allocate a UDP socket structure */
	sock = (UDPsocket)malloc(sizeof(*sock));
	if ( sock == NULL ) {
		SDLNet_SetError("Out of memory");
		goto error_return;
	}
	memset(sock, 0, sizeof(*sock));
	
	/* Open the socket */
#ifdef MACOS_OPENTRANSPORT
	{
		sock->error = OTAsyncOpenEndpoint(
			OTCreateConfiguration(kUDPName),0, &(sock->info),
			(OTNotifyProcPtr)AsyncUDPNotifier, sock );
		AsyncUDPPopEvent( sock );
		while( !sock->error && !( sock->completion & CompleteMask(T_OPENCOMPLETE)))
		{
			AsyncUDPPopEvent( sock );
		}
		if( sock->error )
		{
			SDLNet_SetError("Could not open UDP socket");
			goto error_return;
		}
		// Should we ??
		// (01/05/03 minami<*****@*****.**>
		OTSetBlocking( sock->channel );
	}
#else
	sock->channel = socket(AF_INET, SOCK_DGRAM, 0);
#endif /* MACOS_OPENTRANSPORT */

	if ( sock->channel == INVALID_SOCKET ) 
	{
		SDLNet_SetError("Couldn't create socket");
		goto error_return;
	}

#ifdef MACOS_OPENTRANSPORT
	{
	InetAddress required, assigned;
	TBind req_addr, assigned_addr;
	OSStatus status;
	InetInterfaceInfo info;
		
		memset(&assigned_addr, 0, sizeof(assigned_addr));
		assigned_addr.addr.maxlen = sizeof(assigned);
		assigned_addr.addr.len = sizeof(assigned);
		assigned_addr.addr.buf = (UInt8 *) &assigned;
		
		if ( port ) {
			status = OTInetGetInterfaceInfo( &info, kDefaultInetInterface );
			if( status != kOTNoError )
				goto error_return;
			OTInitInetAddress(&required, port, info.fAddress );
			req_addr.addr.maxlen = sizeof( required );
			req_addr.addr.len = sizeof( required );
			req_addr.addr.buf = (UInt8 *) &required;
		
			sock->error = OTBind(sock->channel, &req_addr, &assigned_addr);
		} else {
			sock->error = OTBind(sock->channel, nil, &assigned_addr );
		}
		AsyncUDPPopEvent(sock);

		while( !sock->error && !(sock->completion & CompleteMask(T_BINDCOMPLETE)))
		{
			AsyncUDPPopEvent(sock);
		}	
		if (sock->error != noErr)
		{
			SDLNet_SetError("Couldn't bind to local port, OTBind() = %d",(int) status);
			goto error_return;
		}

		sock->address.host = assigned.fHost;
		sock->address.port = assigned.fPort;
		
#ifdef DEBUG_NET
		printf("UDP open host = %d, port = %d\n", assigned.fHost, assigned.fPort );
#endif
	}
#else
	/* Bind locally, if appropriate */
	if ( port )
	{
		struct sockaddr_in sock_addr;
		memset(&sock_addr, 0, sizeof(sock_addr));
		sock_addr.sin_family = AF_INET;
		sock_addr.sin_addr.s_addr = INADDR_ANY;
		sock_addr.sin_port = SDL_SwapBE16(port);

		/* Bind the socket for listening */
		if ( bind(sock->channel, (struct sockaddr *)&sock_addr,
				sizeof(sock_addr)) == SOCKET_ERROR ) {
			SDLNet_SetError("Couldn't bind to local port");
			goto error_return;
		}
		/* Fill in the channel host address */
		sock->address.host = sock_addr.sin_addr.s_addr;
		sock->address.port = sock_addr.sin_port;
	}

	/* Allow LAN broadcasts with the socket */
	{ int yes = 1;
		setsockopt(sock->channel, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes));
	}
#endif /* MACOS_OPENTRANSPORT */

	/* The socket is ready */
	
	return(sock);

error_return:
#ifdef MACOS_OPENTRANSPORT
	if( dummy )
		OTCloseProvider( dummy );
#endif
	SDLNet_UDP_Close(sock);
	
	return(NULL);
}
Example #18
0
SDL_AudioSpec * SDL_LoadWAV_RW (SDL_RWops *src, int freesrc,
		SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
{
	int was_error;
	Chunk chunk;
	int lenread;
	int MS_ADPCM_encoded, IMA_ADPCM_encoded;
	int samplesize;

	/* WAV magic header */
	Uint32 RIFFchunk;
	Uint32 wavelen;
	Uint32 WAVEmagic;

	/* FMT chunk */
	WaveFMT *format = NULL;

	/* Make sure we are passed a valid data source */
	was_error = 0;
	if ( src == NULL ) {
		was_error = 1;
		goto done;
	}
		
	/* Check the magic header */
	RIFFchunk	= SDL_ReadLE32(src);
	wavelen		= SDL_ReadLE32(src);
	if ( wavelen == WAVE ) { /* The RIFFchunk has already been read */
		WAVEmagic = wavelen;
		wavelen   = RIFFchunk;
		//RIFFchunk = RIFF;
	}
	if (RIFFchunk != RIFF) {
	RIFFchunk	= SDL_ReadBE32(src);
	wavelen		= SDL_ReadBE32(src);
		if ( wavelen == WAVE ) { /* The RIFFchunk has already been read */
			WAVEmagic = wavelen;
			wavelen   = RIFFchunk;
			RIFFchunk = RIFX;
		}
	}
	if ( wavelen != WAVE )
	{
		WAVEmagic = SDL_ReadLE32(src);
	}
	if (((RIFFchunk != RIFF) && (RIFFchunk != RIFX)) || (WAVEmagic != WAVE)) {
		SDL_SetError("Unrecognized file type %f (not WAVE)", WAVEmagic);
		was_error = 1;
		goto done;
	}
	if (RIFFchunk == RIFF) {
	/* Read the audio data format chunk */
	chunk.data = NULL;
	do {
		if ( chunk.data != NULL ) {
			free(chunk.data);
		}
		lenread = ReadChunk(src, &chunk);
		if ( lenread < 0 ) {
			was_error = 1;
			goto done;
		}
	} while ( (chunk.magic == FACT) || (chunk.magic == LIST) );

	/* Decode the audio data format */
	format = (WaveFMT *)chunk.data;
	if ( chunk.magic != FMT ) {
		SDL_SetError("Complex WAVE files not supported");
		was_error = 1;
		goto done;
	}
	MS_ADPCM_encoded = IMA_ADPCM_encoded = 0;
	switch (SDL_SwapLE16(format->encoding)) {
		case PCM_CODE:
			/* We can understand this */
			break;
		case MS_ADPCM_CODE:
			/* Try to understand this */
			if ( InitMS_ADPCM(format) < 0 ) {
				was_error = 1;
				goto done;
			}
			MS_ADPCM_encoded = 1;
			break;
		case IMA_ADPCM_CODE:
			/* Try to understand this */
			if ( InitIMA_ADPCM(format) < 0 ) {
				was_error = 1;
				goto done;
			}
			IMA_ADPCM_encoded = 1;
			break;
		default:
			SDL_SetError("Unknown WAVE data format: %f", SDL_SwapLE16(format->encoding));
			was_error = 1;
			goto done;
	}
	memset(spec, 0, (sizeof *spec));
	spec->freq = SDL_SwapLE32(format->frequency);
	switch (SDL_SwapLE16(format->bitspersample)) {
		case 4:
			if ( MS_ADPCM_encoded || IMA_ADPCM_encoded ) {
				spec->format = AUDIO_S16;
			} else {
				was_error = 1;
			}
			break;
		case 8:
			spec->format = AUDIO_U8;
			break;
		case 16:
			spec->format = AUDIO_S16;
			break;
		default:
			was_error = 1;
			break;
	}
	if ( was_error ) {
		SDL_SetError("Unknown %d-bit PCM data format",
			SDL_SwapLE16(format->bitspersample));
		goto done;
	}
	spec->channels = (Uint8)SDL_SwapLE16(format->channels);
	spec->samples = 4096;		/* Good default buffer size */

	/* Read the audio data chunk */
	*audio_buf = NULL;
	do {
		if ( *audio_buf != NULL ) {
			free(*audio_buf);
		}
		lenread = ReadChunk(src, &chunk);
		if ( lenread < 0 ) {
			was_error = 1;
			goto done;
		}
		*audio_len = lenread;
		*audio_buf = chunk.data;
	} while ( chunk.magic != DATA );
} else {
	/* Read the audio data format chunk */
	chunk.data = NULL;
	do {
		if ( chunk.data != NULL ) {
			free(chunk.data);
		}
		lenread = ReadChunkBe(src, &chunk);
		if ( lenread < 0 ) {
			was_error = 1;
			goto done;
		}
	} while ( (chunk.magic == FACT) || (chunk.magic == LIST) );

	/* Decode the audio data format */
	format = (WaveFMT *)chunk.data;
	if ( chunk.magic != FMT ) {
		SDL_SetError("Complex WAVE files not supported");
		was_error = 1;
		goto done;
	}
	MS_ADPCM_encoded = IMA_ADPCM_encoded = 0;

	switch (SDL_SwapBE16(format->encoding)) {
		case PCM_CODE:
			/* We can understand this */
			break;
		case MS_ADPCM_CODE:
			/* Try to understand this */
			if ( InitMS_ADPCM(format) < 0 ) {
				was_error = 1;
				goto done;
			}
			MS_ADPCM_encoded = 1;
			break;
		case IMA_ADPCM_CODE:
			/* Try to understand this */
			if ( InitIMA_ADPCM(format) < 0 ) {
				was_error = 1;
				goto done;
			}
			IMA_ADPCM_encoded = 1;
			break;
		default:
			SDL_SetError("Unknown WAVE data format: 0x%.4x", SDL_SwapBE16(format->encoding));
			was_error = 1;
			goto done;
	}
	memset(spec, 0, (sizeof *spec));
			spec->freq = SDL_SwapBE32(format->frequency);

	switch (SDL_SwapBE16(format->bitspersample)) {
		case 4:
			if ( MS_ADPCM_encoded || IMA_ADPCM_encoded ) {
				spec->format = AUDIO_S16;
			} else {
				was_error = 1;
			}
			break;
		case 8:
			spec->format = AUDIO_U8;
			break;
		case 16:
			spec->format = AUDIO_S16;
			break;
		default:
			was_error = 1;
			break;
		}
	if ( was_error ) {

		SDL_SetError("Unknown %d-bit PCM data format",
			SDL_SwapBE16(format->bitspersample));

		goto done;
	}
		spec->channels = (Uint8)SDL_SwapBE16(format->channels);

	spec->samples = 4096;		/* Good default buffer size */

	/* Read the audio data chunk */
	*audio_buf = NULL;
	do {
		if ( *audio_buf != NULL ) {
			free(*audio_buf);
		}
		lenread = ReadChunkBe(src, &chunk);
		if ( lenread < 0 ) {
			was_error = 1;
			goto done;
		}
		*audio_len = lenread;
		*audio_buf = chunk.data;
	} while ( chunk.magic != DATA );
}
	if ( MS_ADPCM_encoded ) {
		if ( MS_ADPCM_decode(audio_buf, audio_len) < 0 ) {
			was_error = 1;
			goto done;
		}
	}
	if ( IMA_ADPCM_encoded ) {
		if ( IMA_ADPCM_decode(audio_buf, audio_len) < 0 ) {
			was_error = 1;
			goto done;
		}
	}

	/* Don't return a buffer that isn't a multiple of samplesize */
	samplesize = ((spec->format & 0xFF)/8)*spec->channels;
	*audio_len &= ~(samplesize-1);

done:
	if ( format != NULL ) {
		free(format);
	}
	if ( freesrc && src ) {
		SDL_RWclose(src);
	}
	if ( was_error ) {
		spec = NULL;
	}
	return(spec);
}
Example #19
0
void   SDLNet_Write16(Uint16 value, void *areap)
{
	(*(Uint16 *)(areap) = SDL_SwapBE16(value));
}
Example #20
0
File: msa.c Project: denizt/hatari
/**
 * Save compressed .MSA file from memory buffer. Returns true is all OK
 */
bool MSA_WriteDisk(const char *pszFileName, Uint8 *pBuffer, int ImageSize)
{
#ifdef SAVE_TO_MSA_IMAGES

	MSAHEADERSTRUCT *pMSAHeader;
	unsigned short int *pMSADataLength;
	Uint8 *pMSAImageBuffer, *pMSABuffer, *pImageBuffer;
	Uint16 nSectorsPerTrack, nSides, nCompressedBytes, nBytesPerTrack;
	bool nRet;
	int nTracks,nBytesToGo,nBytesRun;
	int Track,Side;

	/* Allocate workspace for compressed image */
	pMSAImageBuffer = (Uint8 *)malloc(MSA_WORKSPACE_SIZE);
	if (!pMSAImageBuffer)
	{
		perror("MSA_WriteDisk");
		return false;
	}

	/* Store header */
	pMSAHeader = (MSAHEADERSTRUCT *)pMSAImageBuffer;
	pMSAHeader->ID = SDL_SwapBE16(0x0E0F);
	Floppy_FindDiskDetails(pBuffer,ImageSize, &nSectorsPerTrack, &nSides);
	pMSAHeader->SectorsPerTrack = SDL_SwapBE16(nSectorsPerTrack);
	pMSAHeader->Sides = SDL_SwapBE16(nSides-1);
	pMSAHeader->StartingTrack = SDL_SwapBE16(0);
	nTracks = ((ImageSize / NUMBYTESPERSECTOR) / nSectorsPerTrack) / nSides;
	pMSAHeader->EndingTrack = SDL_SwapBE16(nTracks-1);

	/* Compress image */
	pMSABuffer = pMSAImageBuffer + sizeof(MSAHEADERSTRUCT);
	for (Track = 0; Track < nTracks; Track++)
	{
		for (Side = 0; Side < nSides; Side++)
		{
			/* Get track data pointer */
			nBytesPerTrack = NUMBYTESPERSECTOR*nSectorsPerTrack;
			pImageBuffer = pBuffer + (nBytesPerTrack*Side) + ((nBytesPerTrack*nSides)*Track);

			/* Skip data length (fill in later) */
			pMSADataLength = (Uint16 *)pMSABuffer;
			pMSABuffer += sizeof(Uint16);

			/* Compress track */
			nBytesToGo = nBytesPerTrack;
			nCompressedBytes = 0;
			while (nBytesToGo > 0)
			{
				nBytesRun = MSA_FindRunOfBytes(pImageBuffer,nBytesToGo);
				if (nBytesRun == 0)
				{
					/* Just copy byte */
					*pMSABuffer++ = *pImageBuffer++;
					nCompressedBytes++;
					nBytesRun = 1;
				}
				else
				{
					/* Store run! */
					*pMSABuffer++ = 0xE5;               /* Marker */
					*pMSABuffer++ = *pImageBuffer;      /* Byte, and follow with 16-bit length */
					do_put_mem_word(pMSABuffer, nBytesRun);
					pMSABuffer += sizeof(Uint16);
					pImageBuffer += nBytesRun;
					nCompressedBytes += 4;
				}
				nBytesToGo -= nBytesRun;
			}

			/* Is compressed track smaller than the original? */
			if (nCompressedBytes < nBytesPerTrack)
			{
				/* Yes, store size */
				do_put_mem_word(pMSADataLength, nCompressedBytes);
			}
			else
			{
				/* No, just store uncompressed track */
				do_put_mem_word(pMSADataLength, nBytesPerTrack);
				pMSABuffer = ((Uint8 *)pMSADataLength) + 2;
				pImageBuffer = pBuffer + (nBytesPerTrack*Side) + ((nBytesPerTrack*nSides)*Track);
				memcpy(pMSABuffer,pImageBuffer, nBytesPerTrack);
				pMSABuffer += nBytesPerTrack;
			}
		}
	}

	/* And save to file! */
	nRet = File_Save(pszFileName,pMSAImageBuffer, pMSABuffer-pMSAImageBuffer, false);

	/* Free workspace */
	free(pMSAImageBuffer);

	return nRet;

#else   /*SAVE_TO_MSA_IMAGES*/

	/* Oops, cannot save */
	return false;

#endif  /*SAVE_TO_MSA_IMAGES*/
}
Example #21
0
File: msa.c Project: denizt/hatari
/**
 * Uncompress .MSA data into a new buffer.
 */
Uint8 *MSA_UnCompress(Uint8 *pMSAFile, long *pImageSize)
{
	MSAHEADERSTRUCT *pMSAHeader;
	Uint8 *pMSAImageBuffer, *pImageBuffer;
	Uint8 Byte,Data;
	int i,Track,Side,DataLength,NumBytesUnCompressed,RunLength;
	Uint8 *pBuffer = NULL;

	*pImageSize = 0;

	/* Is an '.msa' file?? Check header */
	pMSAHeader = (MSAHEADERSTRUCT *)pMSAFile;
	if (pMSAHeader->ID == SDL_SwapBE16(0x0E0F))
	{
		/* First swap 'header' words around to PC format - easier later on */
		pMSAHeader->SectorsPerTrack = SDL_SwapBE16(pMSAHeader->SectorsPerTrack);
		pMSAHeader->Sides = SDL_SwapBE16(pMSAHeader->Sides);
		pMSAHeader->StartingTrack = SDL_SwapBE16(pMSAHeader->StartingTrack);
		pMSAHeader->EndingTrack = SDL_SwapBE16(pMSAHeader->EndingTrack);

		/* Create buffer */
		pBuffer = malloc((pMSAHeader->EndingTrack - pMSAHeader->StartingTrack + 1)
		                 * pMSAHeader->SectorsPerTrack * (pMSAHeader->Sides + 1)
		                 * NUMBYTESPERSECTOR);
		if (!pBuffer)
		{
			perror("MSA_UnCompress");
			return NULL;
		}

		/* Set pointers */
		pImageBuffer = (Uint8 *)pBuffer;
		pMSAImageBuffer = (Uint8 *)((unsigned long)pMSAFile + sizeof(MSAHEADERSTRUCT));

		/* Uncompress to memory as '.ST' disk image - NOTE: assumes 512 bytes
		 * per sector (use NUMBYTESPERSECTOR define)!!! */
		for (Track = pMSAHeader->StartingTrack; Track <= pMSAHeader->EndingTrack; Track++)
		{
			for (Side = 0; Side < (pMSAHeader->Sides+1); Side++)
			{
				int nBytesPerTrack = NUMBYTESPERSECTOR*pMSAHeader->SectorsPerTrack;

				/* Uncompress MSA Track, first check if is not compressed */
				DataLength = do_get_mem_word(pMSAImageBuffer);
				pMSAImageBuffer += sizeof(short int);
				if (DataLength == nBytesPerTrack)
				{
					/* No compression on track, simply copy and continue */
					memcpy(pImageBuffer, pMSAImageBuffer, nBytesPerTrack);
					pImageBuffer += nBytesPerTrack;
					pMSAImageBuffer += DataLength;
				}
				else
				{
					/* Uncompress track */
					NumBytesUnCompressed = 0;
					while (NumBytesUnCompressed < nBytesPerTrack)
					{
						Byte = *pMSAImageBuffer++;
						if (Byte != 0xE5)                 /* Compressed header?? */
						{
							*pImageBuffer++ = Byte;       /* No, just copy byte */
							NumBytesUnCompressed++;
						}
						else
						{
							Data = *pMSAImageBuffer++;    /* Byte to copy */
							RunLength = do_get_mem_word(pMSAImageBuffer);  /* For length */
							/* Limit length to size of track, incorrect images may overflow */
							if (RunLength+NumBytesUnCompressed > nBytesPerTrack)
							{
								fprintf(stderr, "MSA_UnCompress: Illegal run length -> corrupted disk image?\n");
								RunLength = nBytesPerTrack - NumBytesUnCompressed;
							}
							pMSAImageBuffer += sizeof(short int);
							for (i = 0; i < RunLength; i++)
								*pImageBuffer++ = Data;   /* Copy byte */
							NumBytesUnCompressed += RunLength;
						}
					}
				}
			}
		}

		/* Set size of loaded image */
		*pImageSize = (unsigned long)pImageBuffer-(unsigned long)pBuffer;
	}

	/* Return pointer to buffer, NULL if failed */
	return(pBuffer);
}
Example #22
0
/* Open a UDP network socket
   If 'port' is non-zero, the UDP socket is bound to a fixed local port.
*/
UDPsocket SDLNet_UDP_Open(unsigned short port)
{
	UDPsocket sock;
	struct sockaddr_in sock_addr;
	socklen_t sock_len;

	/* Allocate a UDP socket structure */
	sock = (UDPsocket)malloc(sizeof(*sock));
	if ( sock == NULL ) {
		SDLNet_SetError("Out of memory");
		goto error_return;
	}
	memset(sock, 0, sizeof(*sock));
	memset(&sock_addr, 0, sizeof(sock_addr));
	
	/* Open the socket */
	sock->channel = socket(AF_INET, SOCK_DGRAM, 0);
	if ( sock->channel == INVALID_SOCKET ) 
	{
		SDLNet_SetError("Couldn't create socket");
		goto error_return;
	}

	/* Bind locally, if appropriate */
	sock_addr.sin_family = AF_INET;
	sock_addr.sin_addr.s_addr = INADDR_ANY;
	sock_addr.sin_port = SDL_SwapBE16(port);

	/* Bind the socket for listening */
	if ( bind(sock->channel, (struct sockaddr *)&sock_addr,
			sizeof(sock_addr)) == SOCKET_ERROR ) {
		SDLNet_SetError("Couldn't bind to local port");
		goto error_return;
	}

	/* Get the bound address and port */
	sock_len = sizeof(sock_addr);
	if ( getsockname(sock->channel, (struct sockaddr *)&sock_addr, &sock_len) < 0 ) {
perror("getsockname");
		SDLNet_SetError("Couldn't get socket address");
		goto error_return;
	}

	/* Fill in the channel host address */
	sock->address.host = sock_addr.sin_addr.s_addr;
	sock->address.port = sock_addr.sin_port;

#ifdef SO_BROADCAST
	/* Allow LAN broadcasts with the socket */
	{ int yes = 1;
		setsockopt(sock->channel, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes));
	}
#endif
#ifdef IP_ADD_MEMBERSHIP
	/* Receive LAN multicast packets on 224.0.0.1
	   This automatically works on Mac OS X, Linux and BSD, but needs
	   this code on Windows.
	*/
	/* A good description of multicast can be found here:
		http://www.docs.hp.com/en/B2355-90136/ch05s05.html
	*/
	/* FIXME: Add support for joining arbitrary groups to the API */
	{
		struct ip_mreq	g;

		g.imr_multiaddr.s_addr = inet_addr("224.0.0.1");
		g.imr_interface.s_addr = INADDR_ANY;
		setsockopt(sock->channel, IPPROTO_IP, IP_ADD_MEMBERSHIP,
			   (char*)&g, sizeof(g));
	}
#endif

	/* The socket is ready */
	
	return(sock);

error_return:
	SDLNet_UDP_Close(sock);
	
	return(NULL);
}
Example #23
0
size_t
SDL_WriteBE16(SDL_RWops * dst, Uint16 value)
{
    const Uint16 swapped = SDL_SwapBE16(value);
    return SDL_RWwrite(dst, &swapped, sizeof (swapped), 1);
}
Example #24
0
void   SDLNet_Write16(unsigned short value, void *areap)
{
	(*(unsigned short *)(areap) = SDL_SwapBE16(value));
}
Example #25
0
static Uint32 neogeo_ROM_read_word ( Uint32 Address )
{
	Uint16	*WordPtr = ( Uint16* ) &neogeo_ROM[Address];
	return SDL_SwapBE16 ( *WordPtr );
}
Example #26
0
unsigned short SDLNet_Read16(void *areap)
{
	return (SDL_SwapBE16(*(unsigned short *)(areap)));
}
Example #27
0
static void neogeo_ROM_write_word ( Uint32 Address, Uint32 Data )
{
	Uint16	*WordPtr = ( Uint16* ) &neogeo_ROM[Address];
	*WordPtr = SDL_SwapBE16 ( Data );
}
static Uint32 neogeo_paletteram_read_word ( Uint32 Address )
{
	Uint16	*WordPtr = ( Uint16* ) &neogeo_palette_RAM[Address + ( ( neogeo_palette_bank & 1 ) * 0x2000 ) ];
	return SDL_SwapBE16 ( *WordPtr );
}
Example #29
0
int SDL_WriteBE16 (SDL_RWops *dst, Uint16 value)
{
    value = SDL_SwapBE16(value);
    return(SDL_RWwrite(dst, &value, (sizeof value), 1));
}
void neogeo_paletteram_write_word ( Uint32 Address, Uint32 Data )
{
	Uint16	*WordPtr = ( Uint16* ) &neogeo_palette_RAM[Address + ( ( neogeo_palette_bank & 1 ) * 0x2000 ) ];
	*WordPtr = SDL_SwapBE16 ( Data );
	video_convert_color ( ( Address / 2 ) + ( ( neogeo_palette_bank & 1 ) * 0x1000 ) );
}