Saturday, December 14, 2013

Recursion vs Iteration




For Some these two terms might heard as trivial ...but recursion solves half of the junk puzzles or most of them unless interviewer does not ask the other way probably iterative.  So this can help
the folks feel that they own these two terms and can use as per the demand. Here we go!!


As per computing , recursion is calling the function from same function itself.  so to understand this we need to know what is the function you are dealing with , what is it supposed to do ...believe me
if you dont think these ..it will bring the avalanche to your terminal. same is valid for iteration.

function is going to be a code block with some arguments , locally scoped, member, global variables, task to do and may be a return. So with these many things inside a room it's surely going to some space in the house. that's what stack and heap gonna to take care in the memory.  when there is call to the function in a running program , which will internally gets converted to CALL address at machine level, this address is going to get pointed by the SP - stack pointer..which means calling function pushes the function reference into the STACK , which is going to need some space out of the memory stack . So when there is recursive call, it adds overhead and needs space for each stack frame. This function placing in stack needs to be kept in mind as this forms the basis of problem solving. And to avoid the "avalanche with an end as stack overflow", this recursion must terminates on some condition probably the base condition for the function task.

for ex :
/*Task for the function is to find the factorial of a number */
long fact(int);

int main() {
    long res;
    int n;
    printf("Enter the number to find the factorial\n");
    scanf("%d", &n);
    if  (n < 0 )  return -1 ;
    else {
         res = fact(n);
         printf("factorial of %d is %ld" , n , res);
    }


    return 0;
}

long fact(int n) {
        /*base condition !0 = 1*/
       if (n==0)
          return 1;
      else
          return (n x fact(n-1));
}

the above program is just a trivial factorial program using recursion but from this program onward only , we should start mapping the pictorial representation of recursive function call trace in stack

lets say number is 5 ...then the call from main function will be for 5! ......now this would be first call
for the function

fact(5)->fact(4) ->fact(3) -> fact (2) -> fact(1) -> fact(0) recursive calls i.e every time from the function itself till reaches the base condition <0! = = 1>

but in stack it will lie as

SP->  fact(0)   TOP  /*last call to go to stack as the function returned 1   */
          fact(1)
          fact(2)
          fact(3)
          fact(4)
          fact(5)

and Program Counter has to return back to CALLEE executing address present in the Link Register after the execution of instruction at the CALLED address pointed by Stack Pointer.  So as per LIFO  fact(0) needs to be executed first by  POPing from stack and so on
for every function call from starting the task would be below for every function calls respectively ,
f(5)  = 5 x f(4)
f(4) = 4 x f(3)
f(3) = 3 x f(2)
f(2) = 2 x f(1)
f(1) = 1 x f(0)
f(0) = 0!   /*return 1*/

replacing the function  by its task ..like f(5) = 5 x 4 x f(3) .... so finally it will become f(5) =  5 x4 x 3 x 2 x1 x 1   which is 5!  comes after all the function called address would be POPed from STACK ...or we say its as "STACK UNWINDING" ..unwinding the stack frame one by one.

 res = fact(n)  will be returned at its original calling place  then there is printf to print the final returned value from fact(n) i.e. 5!  = 120 in above example.

Some other interesting problems which use often Recursion are:

Fibonnaci series
Merge Sort
Quick Sort
Binary Searching
Tree Traversal
Pascal's triangle
Tree Ordering
Graph
Tower of Hanoi  etc

we will discuss more problems using Recursion , more likely while dealing with above Algorithms

Iterations :

This is well know : executing the same set of instructions a given number of times until the specified result or condition met.

It should terminate when a condition met. And It does not take any extra space in memory.
Well it also does bring some sort of avalanche but I would rather say that as forever in loop increasing the operation overhead, very high CPU usage but no impact on memory.

simple example could be a for loop for finding the factorial

for (c = 1; c <= n; c++)
    result = result * c;
Now the Question comes Recursion or iteration ?
someone can say iteration for 5! does not have much in background , its simple just be in loop
till 5<=5 and keep on doing 5x4x3x2x1

but how about if we have problem like :
n! + (n/2) ! + (n/4)! + .........
 And many more ....mainly the Trees  where operation will involve both left and right  nodes



More to Compare :

Which one is effective Recursion or Iteration in Multithreading programming or platform?
How about using them in Real time programming?
Which one to prefer while writing android native framework functions?
Which one to use in Kernel programming ?
How about programming environment  with limited Stack size? 

Tuesday, August 20, 2013








RGB to YUV Conversion

Y  = (0.257 * R) + (0.504 * G) + (0.098 * B) + 16

Cr = V =  (0.439 * R) - (0.368 * G) - (0.071 * B) + 128

Cb = U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128

YUV to RGB Conversion

B = 1.164(Y - 16) + 2.018(U - 128)

G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128)

R = 1.164(Y - 16) + 1.596(V - 128)



Q: what does green frame/display signify as visual artifacts ?

That means there is no data to display.

for No data ,the information/data/value, coming with buffer/frame from codec for rendering,  has to be 0 i.e y= 0 u = 0 v = 0.
put y u v  as 0 in YUV to RGB conversion formula.

B < 0 , R < 0 while G > 0 ....Since We have only positive value or the value in range of 0 to 255 for G , so we get to see green display/frame in the above mentioned case.


Saturday, June 8, 2013

V4L2 Tutorial




V4L2 - video for linux 2 is a set of APIs and standards for handling video devices on Linux. Video devices could be camera sensors providing streams, video encoder , video decoder and apart from these there could be analog radio and any output drivers as device. So mainly all the v4l2 devices would be char type device and each devices get represented by its names in the /dev tree like /dev/video. If there is multiple device or video related data, streams then there can be multiple video device names like /dev/video0 , /dev/video1 , basically /dev/videoX. 

Since it provides set of APIs to handle these devices which lies in physical memory region of the system and get juice from kernel. So v4l2 gets integrated with media framework and resides in kernel as v4l2 driver ,helps to integrate the device/sub-device kernel driver with the media framework. 
V4L2 API includes a very long list of driver callbacks to respond to the many ioctl() commands made available to user space.









     


Kernel Side V4L2 Operations : -
a)Opening V4L2 device using v4l2_open()
b) Controlling V4L2 device using v4l2_ioctl()
c) Reading from V4L2 device using v4l2_read()
d) Writing onto V4L2 device using v4l2_write()
e) Polling onto V4L2 device using v4l2_poll()
f) Mmaping v4L2 device using v4l2_mmap()
g) Closing V4L2 device using v4l2_release()

for ex:
fd = open("/dev/video0", O_RDWR);
close(fd)

V4L2 ioctl : 
a)VIDIOC_S_FORMAT
b)VIDIOC_S_CTRL
c)VIDIOC_REQBUFS
d)VIDIOC_QUERYBUF
e)VIDIOC_QBUF
f)VIDIOC_STREAMON
g)VIDIOC_DQBUF
h)VIDIOC_STREAMOFF


Video Buffer :

In video4linux , we have a video buffer layer which acts as medium between v4l2 driver and app(user side). There is video device which will be streaming data(video frames) into video buffers (vb) . So that said it will require to implement calls like buffer allocation , queuing , dequeuing, streaming I/O and other streaming controls like start/stop. Its not just only reduces only driver code but also provides an uniform and standard APIs for app/user side.

To know more in detail : please follow the kernel documentation
https://www.kernel.org/doc/Documentation/video4linux/videobuf








Monday, April 8, 2013

Practice Sets





Practice Set


1. use of volatile and const volatile
2. AAC vs MP3, which is better
3. how to check endianess
4. Shallow copy vs Deep copy
5. Copy Constructor
6. Operator overriding
7. 25 horses 5 racing track and u need to find the fastest three horses in minimum iteration?
8. how does container takes care of AV Sync?
9. Why Audio is master?
10. What is Bayer Image?
11. What is the difference in kmalloc and vmalloc.
12. RTP streaming - frame synchronization and wall clock.
13. OpenMax codec Integration.
14. Copy_from_User and Copy_to_User
15. Use of Neon Instruction
16. Address mapping in device driver
17. pthread, signalling mechanism.
18. structure padding
19. Stagefright A/V Sync.
20. Use of Audio Policy manager.

It's Answer Discussion Time , Please comment your Answers for Favourite Questions!! Hurry Up!!



After getting over with Practice set questions , I dont see any Answers  getting discussed. Ok looks like trivial questions ah

         Answer Time :

1.  use of volatile and const volatile

Both the types are made not to get optimised by compiler.

By defining volatile , its been instructed to compiler not to change variable priority , always check for
its fresh value, Dont pick from cache.

Its best used with the hardware interaction , where we will be having registers to store the state of hw resource.
ex - unsigned int volatile *status_reg;
       unsigned char volatile *reg_addr;
#define set 0x00000001

int res_register_fd( ) {
while((*status_reg&&set) ==0) {
}

return *reg_addr;
}


const identifier with volatile says the register value / variable value can not be modified anytime within the program. It can only be updated by external hardware resource.

So for improving above example for registers storing the hw resource status
we will be declaring variable as :

       unsigned int const volatile *status_reg;
       unsigned char const volatile *reg_addr;


2. AAC is better than MP3 .AAC provides you variable bit rate easily however mp3 would need more effort, better error resilence, better compression , and easy encoding algo. It provides better quality at same bit rate. AAC offers sampling frequencies between 8 kHz and 96 kHz and any number of channels between 1 and 48. Mp3 supports limited channels. AAC has different encoding schemes to provide better compression -

a.AAC - Low Complexity  = AAC/ AAC_LC

b1.HE-AAC v1   aacPlus v1
common name -  eAAC, AAC+, CT-aacPlus
         Encoding - AAC LC + SBR
Standard -
ISO/IEC 14496-3:2001/Amd 1:2003

b2.HE-AAC v2aacPlus v2,  common name - eAAC+, AAC++, Enhanced AAC+
       Encoding - AAC LC + SBR + PS(Parametric Stereo)             
Standard - ISO/IEC 14496-3:2005/Amd 2:2006
c. AAC_ELD -it is a codec targeting speech coding usecases, by meeting the real time requirement of speech codec(low algorithmic delay), as well as providing much better quality than typical AMR-NB/WB codecs that are usually used for speech coding/VOIP apps.




I will make a separate post to discuss more on AAC and different toppings on this - SBR , PS :)


Tuesday, March 19, 2013

MCQ - Multimedia Common Questions

AUDIO:

What are the audio file types , mime types and container formats you are aware of ? 
What is the difference between AAC-LC / AAC+ / eAAC ? 
What is the difference between AMRNB and AMRWB
For which apps AMR is preferred over AAC ? 
Which Music quality is better - MP3 / AAC ? Why ?
Can we play 5.1 channel audio content on android handsets ? If so, in which android releases ?
How do you verify that the audio output of music playback is indeed  correct ? 
What is the audio routing strategy used in android when you have multiple audio output devices such as BT headset, etc ?
What is the difference between Speech recorder and Sound recorder app ? 
What is echo cancellation  noise suppression and audio effects support available in android ?
What is Sampling frequency?What do you mean by 48Khz?
What is bitrate ? what does 128Kbps mean.
What is significance of Audio Flinger and what does it do?
Explain the Threads running in Audio Flinger?
What is the work Mixer thread? How is Fast Mixer thread different.
What is ALSA , How is it interacting with Audio Framework.
What is Periodic Buffer. What are latency, buffer periods and size.
Explain the Audio Encoding/Decoding flow
What is PCM? what is difference between 16-bit and 32-bit PCM
What is difference between Audio Sink and Audio Output
How is Audio Track being written
What would be impact of CBR and VBR on the Audio
How will you take PCM sample dump.

 

VIDEO:

What are the video  file types , mime types and container formats you are aware of ? 
Which video format is preferred in digital TV ? 
How do you convert video of one resolution to another ? 
What is aspect ratio ? what are the standard values used for video ?
What are the raw video formats that can be rendered to any display device ? What is the difference between those raw formats ?
How will you check the frame rate to be 30fps for encoding as well as decoding.
How will you dump the YUV frames.
What is Surface Flinger. How does video rendering happen.
What is hardware composer. How does Composition happen.
What will be the impact if the video buffers get stuck within decoder. and how will you handle. 


CAMERA
 
 1. camera kernel and HAL interaction 2. Sensor data to HAL 3. Sync between preview and Encoding 4. Bayer Format and resolution 5. ISP functionality 6. How does buffer gets exchanged from HAL to driver 7. What driver is doing 8. Preview frame drop 9. camera service functionality 10. flow from start preview till encoding via capture 11. block diagram of camera module . 12 . JPEG encoding flow in general 13 . DCT vs DFT vs Wavelet for JPEG 14. ISO significance 14. 3A need 15. How does a capture wroks Optics perspective 15. video snapshot functionality 16. how will you make use of multiple core to improve capture usecase?16. What will happen with preview and camera buffers if encoder is slower during recording.
 
IMAGE 
What are the video  file types  and mime types of Images you are aware of ? 
What happens when we view a GIF animation file in android device ? 
What are SMIL files and where are they typically used ? 
What are SVG files and where are they typically used ? 
What are PNG files and where are they typically used ? 
what is the difference betewen BMP and WBMP files ? 
Have you found any issues related to slideshow / thumbnails in gallery / sliding through the gallery ?



METADATA:
What is album art ? 
What is genre ?
What is ID3 tag ?
How do you validate the metadata fields ? 


GENERAL:
What are the different types of streaming for multimedia contents ? What is the difference between each of them ? 
How can we create RTSP streamable contents when a normal 3gp file is given ? 
What RTSP servers are you familiar with and which 3gpp standard did those servers support ? 
How did you measure jitter in RTSP/RTP streaming ? 
How do you measure video playback performance and verify audio-video sync ? 
Which multimedia framework is used in Android ? 
What multimedia codecs are used in Android - SW codecs, DSP codecs or HW codecs ? What is the difference between each of them ?
What are the performance issues /  power management related / quality-related issues you have reported ? 
which is the most complex/difficult issue you have found and reported ?
What happens if we rename the extension of media files such as rename .mp3 to .3gp , .3gp to .jpg , etc.. ?

Saturday, March 16, 2013

H.264 CODEC











In some streams,
for SPS there can be 00 00 00 01 67
for PPS there can be 00 00 00 01 68