Tuesday, April 27, 2010

EPL Weekend Review

Game Of The Week: Chelsea 7 – 0 Stoke
Stoke have been unbeaten this year on road. Also they do have the best defense in the league. To score 7 against them under intense pressure is pure class. Chelsea needed to get back to the pole position after their debacle at White Hart Lane to push for the title. What a response. Another great game for them at Anfield next weekend and they would have one hand firmly on the trophy.

Player Of The Week: Scott Parker (West Ham United)
He is of course Mr.West Ham. If it was not for his wonder strike they would still be fighting to avoid relegation. His goal celebration showed how much he loves the club and what respect he has for the manager.     

Goal Of The Week: Nani (Man Utd)
Superb goal by a super player who has at last earned the respect of the fans at TOD. Although scotty parker and Gerrard scored some scorchers over the weekend, but for me Nani’s goal was critical for Man Utd’s push for the title with the game tied at 1-1. He beat Mr.Octopus with a cool chip. He is a sure starter for Man Utd every game, which speaks volume about his improvement over last season.

Grievance Of The Week: Second City Derby (Aston Villa’s Penalty)
It was a poor decision after the replays showed that Johnson got a touch on the ball before tackling Agbonlahor. I say after replays showed coz at first instance I too though it was a penalty. The referee should have been assisted properly by the linesman. Another poor decision that could fuel the TV replay debate. With atleast 10% of the decisions going wrong every other game it’s high time FIFA put their money in advanced technologies to assist the referees. Hopefully there won’t be any such mistakes at the world cup.

Thursday, April 22, 2010

Power Cuts Put Blore In Dark

It is a joke when politicians claim that Bangalore is on par with any major metro in the world. Really!! I have not heard of any big cities in European/American continent suffering from 4 hours of unscheduled power cuts. The politicians who talk about Bangalore being a better place are either grade A morons or doped. What is worse with these power cuts is that there is no advance notification, which would enable the common man to plan accordingly and cope with it. In India I guess we elect the officials to cause us inconvenience rather than improve our lives. Prior to the election these same politicians promise us uninterrupted power, water and “what not” supply. But the day after getting elected they get back to their way of not listening or caring about the public woes. What is even worse, they cut the power in night and I can see the street lights glowing during the day. What are they trying to do is just beyond me. The ministers enjoy uninterrupted power supply through generators in their cozy houses during the peak summer time and it is the common man who got these stupid morons into those houses who continue to sweat through the night. I hope someone comes out with a better solution for all this.
Till then,
Bangalore != World Renowned Metro

Efficient C Coding Guidelines for Embedded Systems

The C language is like a carving knife: simple, sharp, and extremely useful in skilled hands. Like any sharp tool, C can injure people who don’t know how to handle it.
Andrew Koenig


Here are some ways to avoid the injuries. In my next blog on this topic I shall try to post some of the coding guidelines that I follow in detail. The methods mentioned here again are indicative only. Also the methods may or may not be suitable for your embedded application. The methods are general guidelines.

·         Follow Coding Standards
o   Helps in readability and maintenance

·         Set the compiler to highest level of warnings
o   Never allow a warning to get into production code
o   Warning is a ticking time-bomb

·         All switches to have default case

·         Question all the global variables and their needs

·         Make all variables that can be CONST’s to be CONST’s

·         Variables SHOULD be initialized before use

·         Static Analysis
o   Static analysis are always better than testing

·         Avoid Memory Corruption
o   OS, Libraries and application all run in one address space leading to high possibility of memory corruption
o   Avoid memory corruption by
§  initializing pointers before use,
§  taking care of memory boundaries before incrementing/decrementing pointers
§  allocating appropriate stack size while keeping worst case scenario of interrupt and call nesting in mind

·         Avoid blocking calls inside ISR

Monday, April 19, 2010

Optimization Techniques for TI DSP's Using CCS

Although you might have used all the compiler based optimization options like –O3, -pm etc but still your code may not achieve the set performance target. The reasons are many. Poor code and data ordering and not enough information to the compiler to reorganize the code to take advantage of the pipeline depth. Following are some of the proven methods (not exhaustive) that could help you achieve better performance. For more information please download the optimization guides for your processor from TI website (http://www.ti.com/).
·   Memory Alias Disambiguation 
What would happen if the following function is called?
void my_func (int *ptr_in, int *ptr_out)
{
        LDW       *ptr_in++, A0
        ADD       A0, 4, A1
        STW       A1, *ptr_out++
}
The compiler may think that *ptr_in and *ptr_out point to the same memory location leading to memory aliasing and hence the compiler may not optimize this piece of code. In order to avoid memory disambiguation use the restrict keyword. The above maybe rewritten as
void my_func (int restrict *ptr_in, int *ptr_out)
{
        LDW       *ptr_in++, A0
        ADD       A0, 4, A1
        STW       A1, *ptr_out++
}

·   Use Pragmas
PRAGMAS are preprocessor directives that can give extra information to the compiler about the code below. There are various pragmas that can be used like:
o   UNROLL (# of time to unroll)
#pragma UNROLL (2)
for(i = 0; i < Count ; i++)
{
sum += a[i] * x[i];
       }
§  Tells the compiler to unroll the for() loop twice
§  The compiler will generate extra code to handle the case that count is odd
§  The #pragma must come right before the for() loop
§  UNROLL(1) tells the compiler not to unroll a loop
o   MUST_ITERATE (min, max, %factor)
#pragma MUST_ITERATE (10, 100, 2)
for(i = 0; i < Count ; i++)
{
sum += a[i] * x[i];
       }
§  Gives the compiler information about the trip (loop) count
In the code above, we are promising that:
count >= 10, count <= 100, and count % 2 == 0
§  If you break your promise, you might break your code
§  Allows the compiler to remove unnecessary code
§  Modulus (%) factor allows for efficient loop unrolling
§  The #pragma must come right before the for() loop 
o   DATA_ALIGN (variable, 2n alignment)
#pragma DATA_ALIGN (a, 8)
short a[256] = {1, 2, 3,. . . . 256};
#pragma UNROLL (2)
#pragma MUST_ITERATE (10, 100, 2)
for(i = 0; i < Count ; i++)
{
sum += a[i] * x[i];
}
§  Tell compiler to create variables on a 2n boundary
§  Allows use of (double) word-wide optimized loads/stores

·   Adjust structure sizes to power of two
When arrays of structures are involved, the compiler performs a multiply by the structure size to perform the array indexing. If the structure size is a power of 2, an expensive multiply operation will be replaced by an inexpensive shift operation. Thus keeping structure sizes aligned to a power of 2 will improve performance in array indexing.

·   Place frequent case labels first
If the case labels are placed far apart, the compiler will generate if-else-if cascaded code with comparing for each case label and jumping to the action for leg on hitting a label match. By placing the frequent case labels first, you can reduce the number of comparisons that will be performed for frequently occurring scenarios. Typically this means that cases corresponding to the success of an operation should be placed before cases of failure handling.

·   Minimize local variables
If the number of local variables in a function is less, the compiler will be able to fit them into registers. Hence, it will be avoiding frame pointer operations on local variables that are kept on stack. This can result in considerable improvement due to two reasons:
§  All local variables are in registers so this improves performance over accessing them from memory.
§  If no local variables need to be saved on the stack, the compiler will not incur the overhead of setting up and restoring the stack pointer.

·   Reduce number of function parameters
Function calls with large number of parameters may be expensive due to large number of parameter pushes on stack on each call. For the same reason, avoid passing complete structures as parameters. Use pointers and references in such cases.

·   In-line small (1-5 loc) functions
Converting small functions (1 to 5 lines) into in-line will give you big improvements in throughput. In-lining will remove the overhead of a function call and associated parameter passing. But using this technique for bigger functions can have negative impact on performance due to the associated code bloat. Also keep in mind that making a method inline should not increase the dependencies by requiring a explicit header file inclusion when you could have managed by just using a forward reference in the non-inline version.

·   Get same calculations/comparisons out of the loop
for (int i = 0; i < Max;  i++)
{
      if (Val > CONST_VAL)
      {
            ...
      }
      else
      {
            ....
      }
}
This can be optimized as:
if (Val > CONST_VAL)
{
      for (int i = 0; i < Max; i++)
      {
          .....
       }
}
else
{
      for (int i = 0;  i < Max;  i++)
      {
            .....
      }
}

Disappointing Weekend

What a terrible weekend it has been. One of the worst in last few years. I don’t remember a weekend when all the teams I supported lost or all the teams that I despised won. Saturday afternoon began with a huge defeat to RCB (Royal Challengers Bangalore) at the hands of MI (Mumbai Indians). I had thought that this would be a dress rehearsal for the semis or the finals. The poor NRR (net run rate) means RCB are placed third and hence would have to face the in-form team MI in semis. The semis have been shifted to Mumbai due to security reasons and with the home support it will be very very very hard for RCB to get to the finals.


I was hardly getting over the dismal performance of RCB when the Manchester derby yielded a result that could spin the table on its head. I have hated Manchester Utd since I don’t remember when. Hence I always wanted Man City to succeed in the derbies. As usual the men in blue blinked in stoppage time (that is now 3 times this season, twice in the league and once in carling cup). ManU clinched a winner and most importantly gained three points. Man City will now have to perform exceedingly well in the remaining matches to pip spurs to the coveted fourth spot. The weekend killer though was the Chelsea – Spurs game. Spurs started the game at such high tempo that the Chelsea players were left gasping for breath. Spurs beat Arsenal mid-week and now have beaten Chelsea. That’s two title contenders in space of 4 days. Make no mistake, Spurs have been excellent but to beat the table toppers in two match days that’s just shocking. JT was the worst performer for the blues. Schoolboy stuff. Anelka, Drogba, Lampard etc were totally anonymous throughout the game. I wonder if JT is in the right frame of mind to lead Chelsea after the Bridge gate. I just hope that Spurs continue their good form and beat ManU at old trafford next week(which I think is quite unrealistic as spurs are vulnerable away from home). This has been the most exciting year in EPL. I hope Chelsea can win the title and Man City can get the 4th spot.

All the best Chelsea, Man City and RCB.

Monday, April 12, 2010

Intro to Data (Audio-Video) Compression

What is Compression?
Multimedia material is limited in its quality by the capacity of the channel it has to pass through. With respect to analog signals this translates to bandwidth and the SNR limit of the channel. In case of digitised signals the limitation factors are sampling rate and the sample bit-depth, which are related to the bit-rate. Compression can be defined as a technique which tries to produce a signal which is better than the channel it has passed through would normally allow. This means a coder is required at the transmitting end and a decoder is required at the recieving end of the channel.In the digital world encoders accept digital (audio/video) signals at the source bit-rate and convert them to lower bit-rates before passing them through a channel.
How does it work?
Shanon's theory states that, any signal which is predictable does not contain any information. Compression an be achieved by sending only the useful information also known as entropy. The remaining part of the input signal is called the redundancy. It is redundant because it can be predicted from what the decoder has already been sent.Some caution is required when using compression because redundancy can be useful to reconstruct parts of the signal which are lost due to transmission errors. Clearly if redundancy has been removed in a compressor the resulting signal will be less resistant to errors. unless a suitable protection scheme is applied.
Audio Compression
Audio compression relies on perceptual coding. Human auditory system is capable of percieving changes in low frequencies compared to that in high frequencies. It also fails to register energy in some bands when there is more energy in a nearby band. Audio compressors work by raising the noise floor at frequencies where the noise will be masked. A detailed model of the masking properties of the ear is essential to their design. The greater the compression factor required, the more precise the model must be. Predictive coding uses circuitry which uses a knowledge of previous samples to predict the value of the next. It is then only necessary to send the difference between the prediction and the actual value. The receiver contains an identical predictor to which the transmitted difference is added to give the original value. Predictive coders have the advantage that they work on the signal waveform in the time domain and need a relatively short signal history to operate. They cause a relatively short delay in the coding and decoding stages. Sub-band coding splits the audio spectrum up into many different frequency bands to exploit the fact that most bands will contain lower level signals than the loudest one. In spectral coding, a transform of the waveform is computed periodically. Since the transform of an audio signal changes slowly, it need be sent much less often than audio samples. The receiver performs an inverse transform.
Video Compression
Video compression relies on following assumptions. First being human visual sensitivity to noise in the picture is highly dependent on the frequency of the noise. The second is that even in moving pictures there is a great deal of commonality between one picture and the next. Data can be conserved by raising the noise level where it cannot be detected and by sending only the difference between one picture and the next. Practical video compressors must perform a spatial frequency analysis on the input, and then truncate each frequency
individually in a weighted manner. Such a spatial frequency analysis also reveals that in many areas of the picture, only a few frequencies dominate and the remainder are largely absent. Clearly where a frequency is absent no data need be transmitted at all. For moving pictures, exploiting redundancy between pictures, known as inter-coding, gives a higher compression factor. Starting with an intra-coded picture, the subsequent pictures are described only by the way in which they differ from the one before. The difference picture is produced by subtracting every pixel in one picture from the same pixel in the next picture. This difference picture is an image in its own right and can be compressed with an intra-coding process

Wednesday, April 7, 2010

Man Utd Crash Out....

What a come back from Bayern Munich at theater of dreams!! The game started with surprise inclusion of Rooney. Bayern defenders were left gasping by the pace of Utd wingers. The first goal for the red devils arrived on the 3 min mark. A superb drive by Gibson shocked Butt. Minutes later Utd made it 2-0 with Nani scoring through a back flick of Valencia's drive in the box. And then Nani scored again with 4 mins left in the half as terrible marking by bavarian defenders gave him ample space and time to fire into the top of the net. Meanwhile there were some astonishing tackles on Bayern players. Rafael got booked for schoolboy stuff. He had done wonderfully well in containing the threat of Ribbery until then. Now he had to be careful which gave freedom to the winger. As the first half end approached Utd conceded a goal. Terrible defending by Carrick left Olic to beat Van Der Saar and he did that to bring the Germans back into the game. One more goal from the visitors then Utd have to score again. Late first half goal gave confidence to Munich players and they started the second half well. 50 mins gone and Rafael gets booked and gets sentenced for hauling back Ribbery. It was total naivity from the young player. Similar offence had been committed and punished in the Carling cup, but the lad doesn't seem to have learnt from it. Rooney was replaced by John O'Shea and the Germans had their best in terms of possesion. With the Bayern wingers free more chances were created. 16 mins before the end Ribbery took a corenr and setup the ball beautifully to unmarked Robben who controlled it superbly to smash it past Utd defenders and goalie into the bottom corner. The comeback was completed. Bayern munich deserve to be in the semis with their never say die attitude. Utd have now been beaten 3 times in a row. With the financial benefits from Champ Lge gone, their situation may get worse. They may again be forced to sell players in the transfer window. Also Rooney's injury needs to be nursed and SAF will hope that he recovers intime to face Balckburn at the weekend and the local derby at eastlands.

Tuesday, April 6, 2010

Messi - The Mesmerizer

If anyone missed the Barca - Gunners match last night, then they missed seeing a player full in control and confidence. I do not see anyone in the world of football right now who is close to Lionel "the goal machine" Messi. Yes Drogba, Rooney, Pato etc are in the form of their life but Messi has been playing as if he belongs to another planet. In this game he scored the third hatrick of the season. That is just unbelievable from a player who does not seem to have a great physical presence like Drogba, Anelka or Bendtner. Well let me get back to last night's game. Arsenal took a shock lead through Bendtner. Twenty one minutes later the scoreline looked Barca 3 - 1 Arsenal. Hatrick in twenty one minutes in a champions league game says a lot about the class of the man. Yes Arsenal were depleted as Fabregas, Song, Gallas, Arshavin and Campbell missed the game through either through suspension or injury. On the other hand Barca were without their prefered center backs in Puyol and Pique and their first leg scorer Ibramohavic. But then as it turned out, Messi made those absence totally irrelevent with his sheer brilliance. It would be great if Maradona can use him like Guardiola at the World Cup. This would make sure that his trophy cabinet has the missing medal and that would truly qualify for him to be called the "World Footballer of The Year" yet again. I wish Argentina the perenial underachievers to win the coveted trophy at South Africa. Argentinian team would be a force to reckon with players of the quality of Messi, Tevez, Sergio and Angel Di Maria.