Path: blob/master/libs/mpg123/src/common/swap_bytes_impl.h
4389 views
/*1swap_bytes: Swap byte order of samples in a buffer.23copyright 2018 by the mpg123 project4licensed under the terms of the LGPL 2.15see COPYING and AUTHORS files in distribution or http://mpg123.org67initially written by Thomas Orgis89This is C source to include in your code to get the function named10swap_bytes. It is serves intentional duplication in libmpg123 and11libsyn123 to avoid introducing a dependency between them. This function12is too small for that.13*/1415/* Other headers are already included! */1617/* Optionally use platform-specific byteswap macros. */18#ifdef HAVE_BYTESWAP_H19#include <byteswap.h>20#endif2122/* Plain stupid swapping of elements in a byte array. */23/* This is the fallback when there is no native bswap macro. */24#define SWAP(a,b) tmp = p[a]; p[a] = p[b]; p[b] = tmp;2526/* Convert samplecount elements of samplesize bytes each in buffer buf. */27static void swap_bytes(void *buf, size_t samplesize, size_t samplecount)28{29unsigned char *p = buf;30unsigned char *pend = (unsigned char*)buf+samplesize*samplecount;31unsigned char tmp;3233if(samplesize < 2)34return;35switch(samplesize)36{37case 2: /* AB -> BA */38#ifdef HAVE_BYTESWAP_H39{40uint16_t* pp = (uint16_t*)p;41for(; pp<(uint16_t*)pend; ++pp)42*pp = bswap_16(*pp);43}44#else45for(; p<pend; p+=2)46{47SWAP(0,1)48}49#endif50break;51case 3: /* ABC -> CBA */52for(; p<pend; p+=3)53{54SWAP(0,2)55}56break;57case 4: /* ABCD -> DCBA */58#ifdef HAVE_BYTESWAP_H59{60uint32_t* pp = (uint32_t*)p;61for(; pp<(uint32_t*)pend; ++pp)62*pp = bswap_32(*pp);63}64#else65for(; p<pend; p+=4)66{67SWAP(0,3)68SWAP(1,2)69}70#endif71break;72case 8: /* ABCDEFGH -> HGFEDCBA */73#ifdef HAVE_BYTESWAP_H74{75uint64_t* pp = (uint64_t*)p;76for(; pp<(uint64_t*)pend; ++pp)77*pp = bswap_64(*pp);78}79#else80for(; p<pend; p+=8)81{82SWAP(0,7)83SWAP(1,6)84SWAP(2,5)85SWAP(3,4)86}87#endif88break;89/* All the weird choices with the full nested loop. */90default:91for(; p<pend; p+=samplesize)92{93size_t j;94for(j=0; j<samplesize/2; ++j)95{96SWAP(j, samplesize-j-1)97}98}99}100}101102#undef SWAP103104105