PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Scaling an Image to Half-Res

hi all,

i need to downscale large images (640x480) to half-res (320x240). the code below is how i'm currently achieving this. unfortunately it is still too slow.

main slow-down seems to be memory access. any ideas on how to speed it up, such as better using cache-lines by traversing block-wise through memory?

Code:

void
scaleImageRGB565ToHalfRes(const unsigned short* nSrc, unsigned short* nDst, int nWidth, int nHeight)
{
register int x;
int y=nHeight, wh=nWidth/2;

register const unsigned int* srcI = (const unsigned int*)nSrc;
register unsigned int* dstC = (unsigned int*)nDst;

while(y)
{
// even y pos
x = nWidth;
while(x)
{
// read 4 pixels at once
register unsigned int src0 = *srcI++;
register unsigned int src1 = *srcI++;

// produce 2 RGB pixels
*dstC++ = (src0&0x0000ffff) | (src1<<16);

x -= 4;
}

// skip odd y pos
srcI += wh;

y -= 2;
}
}


thx,
Daniel
well, it seems fast, I think the only thing I could optimize would be changing the &0xffff for a & variable, as who knows what is the compiler doing there (might be taking the 0xffff everytime from memory)

also, I don't see the point in loading 4 bytes if you're using only 2, a ldrh should clean the high part of the register, isn't it? This way you could avoid the "&0xffff" part. Again, you depend on the type of code the compiler generates.

I think the best way to see how to improve this is looking at the assembly code generation.

p.s. I've always been told not to use "register" keyword. Nowadays compilers should be intelligent enough to know what to register.

I hope it helps. And I hope I didn't write many lies here ;)
hi Kak,

thanks for sharing your thoughts.
i thought that the processor would have to read 32-bits anyway but i'll give it a try. this code resulted from a routine that also did a RGB565 to gray conversion at full res in the same step. at that time i had to read all pixels...

i thought that some speedup could be gained from using the processor's cache better. i once looked at PocketFrog's swizzle/unswizzle code and it was awfully slow (at that time). i then wrote a routine that rotated the image blockwise and it was several times faster due to better cache usage. i hoped that before i start trying this again maybe somebody already has a working solution...

thx,
Daniel
I think your routine is optimal and Kaks suggestions should not help.

Lets look what the compiler is doing with the inner loop:

|$L28333|
ldr r0, [r2], #4
//the compiler is filling the delay slot(s) by moving the x -= 4; to here
sub r4, r4, #4
cmp r4, #0
ldr r1, [r2], #4
//again the compiler fills delay slots with &, this makes the & basically free
//also note, that the constant is already in R5
and r0, r0, r5
orr r1, r0, r1, lsl #16
str r1, [r3], #4
bhi |$L28333|


As far as the cache is concerned, it wont help you here, since you are only reading and writing data. Caching only helps if you read data in one iteration to be used in other iterations, which is not the case here.
With other words, compilers are pretty clever these days. Even with asm you wont get any faster.

Tala
hi Tala,

thx for analyzing the code.
at least i know that i don't have to optize this on command level anymore.

about the cache thing:
i don't think that what you say is always true. i read a very interesting book called "Code Optimization: Effective Memory Usage". that book is targeted for intel desktop processors but many mechanisms are the same for xscale.
one message from that book was that reading linear is not always the fastest option (at least not on a pentium). if the cpu reads the first DWORD of a cache line then it has to wait for all bytes of that cacheline to be read before it can use any data of that cacheline. if the cpu uses that time to precache another cacheline, etc. then it can use the rest of the first cacheline with less delay since it was already fetched.

so what i think is that pseudo code like this could be faster than linear read:
Code:

for(idx=0; idx<numDwordsPerCacheline; idx++)
for(line=0; line<numCachelines; line++)
dst[line*numDwordsPerCacheline+idx] = src[line*numDwordsPerCacheline+idx] =

anybody any comments on this?

i fear i'll have to try this to really know...
bye,
Daniel
if the cpu reads the first DWORD of a cache line then it has to wait for all bytes of that cacheline to be read before it can use any data of that cacheline.


That not always true, modern caches support "early restart" and "critical word first" concepts. Dont know about the Xscale cache though.

Looking at your example i dont see how this can be faster, since your first inner loop only produce misses. So the total amount of misses is the same.
What you really need is a prefetch instruction, which can be processed asynchronously whitout waiting for the data (in contrary to a read to the particular chacheline).

Your example may be useful, if th cache support "hit under miss" or "miss under miss". This however is only effective if the CPU support out of order completion, which ARM does not support.

Tala
What you really need is a prefetch instruction, which can be processed asynchronously whitout waiting for the data (in contrary to a read to the particular chacheline).

so that would be __prefetch()

(http://msdn.microsoft.com/library/defau ... efresh.asp)

does anybody know if that funciton actually does what i need? the MSDN docs are very brief...

bye,
Daniel
Tala wrote:
sub r4, r4, #4
cmp r4, #0


-> subs r4,r4,#4 ?
xscale architecture has a new instruction named "PLD" for PreLoaD, and it's extremely useful to avoid cache miss when you know in advance that you'll have to read a memory area.

You can read the source code of the optimized "memcpy" function given by intel as an example.

However, to find the best way to use it in a specific routine you'll have to bench your code and try...
-> subs r4,r4,#4 ?


AFAIK Xscale has 3 load use delay slots, so it should not make a difference.

xscale architecture has a new instruction named "PLD" for PreLoaD, and it's extremely useful to avoid cache miss when you know in advance that you'll have to read a memory area.


Of course one would have to use assembly then. Or do you know a way to give the compiler prefetch hints from C?

Tala
Get rid of x and y and use your pointers to determine when to break out of the loops. Your loops are already pretty tight, so if they aren't close to stalling out then that should help.

Dan East
hi all,

changing the counter to a pointer did not change a thing (as i expected), but i added my cache preloading idea and it rocks. conversion time went down from 6.5ms to 3.0ms, (converting 640x480 to 320x240) so that's a speedup of more than 100% by just adding three lines of code...

here's the new code. the only thing i really added is the while(--i) loop. i calculate a variable dummy in that loop to prevent the compiler from optimizing the loop away.

Code:

int
scaleImageRGB565ToHalfRes_v1(const unsigned short* nSrc, unsigned short* nDst, int nWidth, int nHeight)
{
int y=nHeight, wh=nWidth/2;

const unsigned int* srcI = (const unsigned int*)nSrc;
unsigned int* dstC = (unsigned int*)nDst;
register int dummy = 0;
int i;

while(y)
{
// even y pos
//
unsigned int* dstCLineEnd = dstC + nWidth/4;

// preload 2*nWidth bytes into 2*nWidth/32 cache lines (32 bytes each by reading one DWORD from each cacheline)
// use a dummy to force reading of data
i = 2*nWidth/32 + 1;
while(--i)
dummy += srcI[i*8];


while(dstC<dstCLineEnd)
{
// read 8 pixels at once
unsigned int src0 = *srcI++;
unsigned int src1 = *srcI++;
unsigned int src2 = *srcI++;
unsigned int src3 = *srcI++;

// produce 4 RGB pixels
*dstC++ = (src0&0x0000ffff) | (src1<<16);
*dstC++ = (src2&0x0000ffff) | (src3<<16);
}

// skip odd y pos
//
srcI += wh;

y -= 2;
}

return dummy;
}


further loop unrolling slowed down performance. so i think we already reached quite an optimum. at this speed memory is read at ~200MB/sec and written at 50MB/sec.

it's nice to see that making proper use of the cache (by adding just 3 lines of code) can result in a speedup of over 100% for already optimized code.

just a side notice: on a 1.7GHz Pentium-M (which obviously fully runs my benchmark in the cache) the conversion is done in 0.12ms...

bye,
Daniel
oki, once more...

i changed the precaching routine to this:
Code:

i = nWidth/2 - 32; // same as: i = (2*nWidth/32)*8 - 32;
while(i>=0)
{
dummy0 += srcI[i+ 0];
dummy1 += srcI[i+ 8];
dummy2 += srcI[i+16];
dummy3 += srcI[i+24];
i -= 32;
}

the difference is that the CPU is now reading the first DWORD from each cacheline into a different register (dummy0-dummy3). as the xscale documentation states, the xscale has 4 fill buffers which can only work in parallel if 4 independent read requests are open.

the speedup is not that impressive anymore but still goes from 3.06ms to 2.88ms which is another 6% or almost 130% from the original (already optimized) code that did not preload the cache.

Daniel
Using assembly (with the PLD instruction) could save you the dummy load.

I'm sure you can still get more bandwidth, but it's hard to find the perfect preloading code...
hmm, i doubt that using PLD would result in even higher cache-reloading performance but it would be interesting to test this. an advantage of using the dummy register is that it works with pure C.

does anybody have a lib that exports PLD to C so i could try it?

thx,
Daniel
drgoldie wrote:hmm, i doubt that using PLD would result in even higher cache-reloading performance


You may want to take a look at this interessting article :

http://www.google.fr/search?q=cache:BXO ... mcpy&hl=fr



does anybody have a lib that exports PLD to C so i could try it?


http://msdn.microsoft.com/library/defau ... reload.asp
hi stephC,

thanks for that hint.
strange thing is that using the _Preload function the code actually becomes slower.
i changed my previous code to not add, but just read from memory and the time went down to 2.04ms. on the other hand the PLD version takes 3.71ms.

the problem seems to be that in the LDR case the compiler creates the following:

ldr r0, [r2]
ldr lr, [r2, #0x20]
ldr r11, [r2, #0x40]
ldr r10, [r2, #0x60]

while in the PLD case it updates the address register all the time which prevents it from being used for PLD next clock circle.

any ideas on this? i'd still be interested to see how fast an optimal PLD solution would be. maybe somebody could create a 'precompiled' assembler function that can preload x bytes using PLD (i'm not an assembler programmer). i'd love to check how fast that would be...

besides that i'm happy to see that this code now got more than 3x faster than the original implementation that looked already fully optimized...

Daniel
Not sure how you used the pld instruction, but it is supposed to be used within the inner loop, not prior to it.

I made a little example by basically using the compiled code from your first post and added one PLD instruction in the load delay slot of the second load. I bet you can further improve this slightly by loop unrolling.

Code:

AREA scale,CODE,READONLY
EXPORT scaleImageRGB565ToHalfRes_pld


scaleImageRGB565ToHalfRes_pld
stmdb sp!, {r4 - r8, lr}
mov r6, r0
mov r5, r1
mov r4, r2
mov r7, r3
add r0, r4, r4, lsr #31
mov r1, r0, asr #1
cmp r7, #0
beq |END|
mov r8, #0xFF, 24
mov r3, r1, lsl #2
orr r8, r8, #0xFF
|OUTER_LOOP|
mov r2, r4
cmp r4, #0
beq |INNER_LOOP_END|
|INNER_LOOP|
ldr r0, [r6], #4
subs r2, r2, #4
ldr r1, [r6], #4
and r0, r0, r8
pld [r6,#32]
orr r1, r0, r1, lsl #16
str r1, [r5], #4
bne |INNER_LOOP|
|INNER_LOOP_END|
add r6, r6, r3
subs r7, r7, #2
bne |OUTER_LOOP|
|END|
ldmia sp!, {r4 - r8, pc}

END


Tala
hi Tala,

thanks for the code.
i hate to say so but it is a lot slower (3.53ms) than my current C version (2.03ms).

Daniel
Guess one needs to experiment a bit more, since PLDs should always be preferred to loads since they are not blocking, can be done speculatively and do not use registers.
What timer do you use to measure performance?

Tala
i use GetTickCount(). i do 2000 calls to the scale function - so the measurement should be quite accurate.

do you want my source to test it on your own?
i'd be very interested in a fast implementation of this function but 2ms is already quite good for me...

bye,
Daniel
do you want my source to test it on your own?


Yes, that would be useful. As far i did not get faster than 2.26 ms and i am running out of ideas :)

What puzzles me somewhat is:

Code:

int y=nHeight, wh=nWidth/2;


isnt wh supposed to be nWidth*2? (2 bytes per pixel).

Tala

edit: srcI is of type unsigned int* so i guess its correct. i always get confused when i work on asm and c at the same time. The compiler correctly assigns 2*640 to the register containing wh :)
oki, here's the code:
http://www.ims.tuwien.ac.at/~daniel/dow ... aleImg.zip

and you'll need my tool library for loading the image:
http://www.ims.tuwien.ac.at/~daniel/dow ... tknife.zip

the program reads a jpp in 640x480 and writes a tga in 320x240. the conversion is done 2000 times...

edit: _v2 in that is the fastest, not _v3...

Daniel
Yes i found your version faster too, still i fail to understand why. The pld is supposed to be used for constant prefetchign ahead, in my implementation 3 chachelines ahaed. I also found, that you cannot conditionally execute PLDs (thought ARMASM does not complain !), so i had to use a conditional branch.

Here is the actualy code, i dont think its gonna be faster this way unless i am doing something seriously wrong.

Code:
scaleImageRGB565ToHalfRes_pld
stmdb sp!, {r4 - r10, lr}
mov r6, r0
pld [r6]
pld [r6,#32]
pld [r6,#64]
pld [r6,#96]
mov r5, r1
mov r4, r2
mov r7, r3
add r0, r4, r4, lsr #31
mov r1, r0, asr #1
cmp r7, #0
beq |END|
mov r8, #0xFF, 24
mov r3, r1, lsl #2
orr r8, r8, #0xFF
|OUTER_LOOP|
mov r2, r4

|INNER_LOOP|

ldmia r6!, {r0,r1,r9,r10}
cmp r2,#64
bmi |NEGATIVE|
pld [r6,#112]

|CONT|
and r0, r0, r8
orr r1, r0, r1, lsl #16
and r9, r9, r8
orr r10, r9, r10, lsl #16
stmia r5!, {r1,r10}

ldmia r6!, {r0,r1,r9,r10}
subs r2,r2,#16
and r0, r0, r8
orr r1, r0, r1, lsl #16
and r9, r9, r8
orr r10, r9, r10, lsl #16
stmia r5!, {r1,r10}

bne |INNER_LOOP|

|INNER_LOOP_END|
add r6, r6, r3
subs r7, r7, #2
bne |OUTER_LOOP|

|END|
ldmia sp!, {r4 - r10, pc}

|NEGATIVE|
pld [r6,#1392]
b |CONT|



Tala
hi Tala,

thanks for the updated code.
unfortunately it's still slower (3.04ms) than my C version (2.05ms).

Daniel
Are you copying the preload example from the Intel site? I wonder if their example assumes that process( a ) does a fair bit more work than this example, i.e the work takes about as long as the prefetch. If you're only asking for data 4 elements ahead, then given the relatively small inner loop, you might run out before your data is in the cache. You could try preloading n blocks ahead instead of just 1?
joshbu [MSFT] · 16 Sep 2005, 21:38 UTC
You could cut the number of reads in half by using a slightly modified point sample. Right now, it looks like you are selecting pixels 0, 2, 4, 6, ... If you select pixels 0, 1, 4, 5, 8, 9, ... you'd only have to read every other dword of your source.

There would obviously be a loss in image quality, but if you're working primarily with photos or better, video, that might be OK.

Also, I'm sure it's been noted here before, but doing integer downsamples with RLE is pretty easy, and can be fast. (Mind the rounding! :wink: )
interesting idea.

besides reducing the read count to 50% (which should not change that much since the data is in the cache already) it would also remove the need for several bit manipulation operations since the algorithm would then simply copy every 2nd DWORD.

i tried your modification. the image quality degradation is quite visibile. the time to reduce an image from 640x480 to 320x240 goes down from 2.06ms to 1.73ms.

if image quality is not that important then this is a nice (because simple) improvement...

bye,
Daniel
joshbu [MSFT] wrote:You could cut the number of reads in half by using a slightly modified point sample. Right now, it looks like you are selecting pixels 0, 2, 4, 6, ... If you select pixels 0, 1, 4, 5, 8, 9, ... you'd only have to read every other dword of your source.


Since a data cache line on the XScale is 32 bytes (16 pixels), you end up reading all the pixels anyways. The speed gain you would get (if any) isn't worth the image quality degradation.
Thierry wrote:Since a data cache line on the XScale is 32 bytes (16 pixels), you end up reading all the pixels anyways. The speed gain you would get (if any) isn't worth the image quality degradation.


If you do it like Joshbu says then you only need one load instruction to nab 2 pixels i.e 0,1,2,3,4,5... (load 0 and 1 are loaded as single 32bit DWORD), then 4 and 5 etc. Whereas if you wanted 0 and 2 you'd have to load them both separately (though u could use LDM and it'd take 1 extra cycle).
as i already posted, the results are not that much faster considering a degration of image quality. i agree to Thierry that skipping reading the pixels will not really make a difference, since data is in the cache anyway. i'm quite sure that the speed difference comes from skiping the bit manipulations.

so this
Code:
unsigned int src0 = *srcI++;
unsigned int src1 = *srcI++;
unsigned int src2 = *srcI++;
unsigned int src3 = *srcI++;

*dstC++ = (src0&0x0000ffff) | (src1<<16);
*dstC++ = (src2&0x0000ffff) | (src3<<16);


becomes to this
Code:
*dstC++ = srcI[0];
*dstC++ = srcI[2];

srcI += 4;


bye,
Daniel
Project just finished so I've had some free time to investigate this for myself, as I thought it'd be rather odd if it didn't actually work.

Direcly replacing the loads with preloads looked lovely in the asm

Code:

pld [r3], #0x20
pld [r3], #0x20
pld [r3], #0x20
pld [r3], #0x20


Saving 4 registers which might be needed in a more complex function.

However, very dissapointingly and consistent with other people's findings, this was significantly slower (though faster than not preloading at all). On a h4190 I got :

Seconds
6.97 - No preloading
2.61 - version 2
4.48 - using PLD instruction

I also tried preloading smaller chunks on the assumption that a large number of preload requests might push older requests out of the request list. This didn't have any significant effect.

Wonder if there are any hardware guys that can explain exactly why this happens?

Anyway, to curb my dissapointment, I thought I'd have a go at optimizing the code a bit and came up with these :

Code:

// MooShort 1.81
int scaleImageRGB565ToHalfRes_MooShort(
const unsigned short* p_sourceData,
unsigned short* p_destData,
unsigned int width,
unsigned int height )
{
unsigned int halfWidth = width>>1;
unsigned short dummy0=0,dummy1=0,dummy2=0,dummy3=0;

do
{
// Preload this line
const unsigned short* p_preloadStart = p_sourceData;
const unsigned short* p_preloadEnd = p_sourceData + width;

do
{
dummy0 = *p_preloadStart;
p_preloadStart += 16;
dummy1 = *p_preloadStart;
p_preloadStart += 16;
dummy2 = *p_preloadStart;
p_preloadStart += 16;
dummy3 = *p_preloadStart;
p_preloadStart += 16;
} while ( p_preloadStart < p_preloadEnd );

unsigned short* p_destLineEnd = p_destData + halfWidth;
do
{
// Copy every other pixel to destination
unsigned short src0 = *p_sourceData;
p_sourceData += 2;
unsigned short src1 = *p_sourceData;
p_sourceData += 2;
unsigned short src2 = *p_sourceData;
p_sourceData += 2;
unsigned short src3 = *p_sourceData;
p_sourceData += 2;

*p_destData++ = src0;
*p_destData++ = src1;
*p_destData++ = src2;
*p_destData++ = src3;
} while ( p_destData < p_destLineEnd );

// Ignore odd lines
p_sourceData += width;
height -= 2;
} while ( height > 0 );

return dummy0+dummy1+dummy2+dummy3;
}


This chappie takes 1.81 secs on my ppc (30% faster)

Code:

// MooUnrolled - 1.75
__forceinline void CopyPixels( unsigned short*& p_destData, const unsigned short*& p_sourceData )
{
unsigned short src0 = *p_sourceData;
p_sourceData += 2;
unsigned short src1 = *p_sourceData;
p_sourceData += 2;
unsigned short src2 = *p_sourceData;
p_sourceData += 2;
unsigned short src3 = *p_sourceData;
p_sourceData += 2;

// produce 4 RGB pixels
*p_destData++ = src0;
*p_destData++ = src1;
*p_destData++ = src2;
*p_destData++ = src3;
}

int scaleImageRGB565ToHalfRes_MooUnrolled(
const unsigned short* p_sourceData,
unsigned short* p_destData,
unsigned int width,
unsigned int height )
{
unsigned int halfWidth = width>>1;
unsigned short dummy0=0,dummy1=0,dummy2=0,dummy3=0;

do
{
// Preload this line
const unsigned short* p_preloadStart = p_sourceData;
const unsigned short* p_preloadEnd = p_sourceData + width;

do
{
dummy0 = *p_preloadStart;
p_preloadStart += 16;
dummy1 = *p_preloadStart;
p_preloadStart += 16;
dummy2 = *p_preloadStart;
p_preloadStart += 16;
dummy3 = *p_preloadStart;
p_preloadStart += 16;
} while ( p_preloadStart < p_preloadEnd );

// Each step does 8 pixels ( -4 is for the first iteration of the loop
unsigned int numSteps = (halfWidth>>2);
while ( true )
{
if ( numSteps >= 8 )
{
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
numSteps -= 8;
}
else if ( numSteps >= 4 )
{
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
CopyPixels( p_destData, p_sourceData );
numSteps -= 4;
}
else if ( numSteps >= 1 )
{
CopyPixels( p_destData, p_sourceData );
numSteps -= 1;
}
else
{
break;
}
};

// Skip odd lines
p_sourceData += width;
height -= 2;
} while ( height > 0 );

return dummy0+dummy1+dummy2+dummy3;
}


Unrolling the inner loop takes this down to 1.75 (33% faster). (You might have to enable inlining in the project)

Still plenty of room for improvement there, it currently (unnecessarily) spills the width onto the stack, there is the unnecessary calculation at the bottom and thats prolly not the best way of unrolling a loop. Anyway.....