Sunday, October 14, 2012

Difference between Static and DHCP ip address:
   In static IP address, We will configure the interface with the our IP address/netmask and so on.
 Whereas in DHCP, we will DHCP client protocol identifies the IP address from DHCP server and send the IP address to kernel via RTM_NEWADDR msg over the netlink.

  

Circular Dependency:

I added new xml to settings due to that I got "Stack overflow error" in android runtime,Settings application was not launched.
        Added xml file is ic_settings_ethernet.xml.





 

ic_settings_ethernet.xml contents:
=======================

https://groups.google.com/forum/?fromgroups=#!msg/rowboat/lP65eylKHkQ/flHykmz15xAJ

The stack overflow is caused by the the res/drawable/ic_settings_ethernet.xml file in packages/apps/Settings which references itself, creating a circular dependency. I could not find any use of this file in any of the other resource files or in the Java source code. Simply removing it allows me to start the Settings app without crashes.

How to disable the WiFi/any networking or add any network in android :
 
  In android framework, there is a file to configure available networks.
If we disabled particular network in that file, Particular network will be disabled in android.

name of the file need to be modified to disable networks:
frameworks/base/core/res/res/values/config.xml

This file contents are as below:
 
  translatable="false" name="networkAttributes">
        "wifi,1,1,1"
        "mobile,0,0,0"
        "mobile_mms,2,0,2"
        "mobile_supl,3,0,2"
        "mobile_dun,4,0,4"
        "mobile_hipri,5,0,3"
    
 
 
In android framework, Connnectivity manager/service is reponsible for handling available networks.
If I want to add new network, I have to develop a service,NetworkStateTracker  and add the content in the above file.
 
 
Let me say If I want to add ethernet support, ethernet service should be written, launched from ConnectivityService.
we need to develop our own NetworkStateTracker derived class to maintain the state of ethernet.
We also need to add new item in the above file.
   From the above file only, Android will comes to know the available networks.
Let me say if I removed the wifi item, then WiFi wont be detected. Because android framework doesnt know the wifi network is available 
 
 
 

How to display logs from android service:

By default,If we added any android service in init.rc, logs are redirected to null device. So logs wont be shown from service. Sometimes it will show sometimes it wont show logs. To display logs always from service,


we have to do the following

service serviceName /system/bin/logwrapper /system/bin/dhcpcd -BKLA -d eth0
disabled
oneshot

/system/bin/logwrapper - this will redirect the  service logs to logcat.

init.rc script is executed by init process.

How to communicate between two process /To pass information from one application to another application in android java:

 Best ways are intents. whoever wants to send message, He has to raise an intent.Whichever Application wants to receive the message, It has to implement  BroadcastStatusReceiver class.

We can raise intent like this... 

Intent sIntent = new Intent(EthernetManager.ETHERNET_STATE_CHANGED_ACTION);
sIntent.putExtra("EthUp",true) //THis is information to be passed
                                                   //Intent has different methods for string/int and   //so on


whoever[applications] wants to receive this intent they register this intent in their androidmanifest.xml, they will implement the BroadcastStatusReceiver for the same.
From the receiver application's BroadcastStatusReciever's OnReceive()
{
   if(recvdIntent.Equals(ETHERNET_STATE_CHANGED_ACTION)
   {
     boolean b=getBooleanExtra("EthUp");
    }


}


To Know the disk freespace in linux

To know the disk freespace in Linux:

=======================================

df [disk free] command


df -k -h

it will list the partition,used space and free space available.



Thursday, October 04, 2012

To Enable logs in android Java files:   

import android.util.Slog;
 private void log(String s) {
        Slog.d(TAG, s);
    }
How to detect IP address change in Linux:

http://stackoverflow.com/questions/579783/how-to-detect-ip-address-change-programmatically-in-linux
Copy all the files except one folder in Linux:

We have to run the following commands:

shopt -s extglob       #setting bash shell option to recognize regex patterns
cp -r A/!(B) dest_dir  #This will copy directory A to dest_dir and
                                 #excludes B directory
Another way of adding NDK logs in C/C++:

#include
LOCAL_LDLIBS := -llog

void LOGI(char *szMsg)
{
__android_log_write(ANDROID_LOG_ERROR,"Tag",szMsg);
}
 Read and print all arguments in C/C++:
===========================
     
  int count;
   for (count = 0; count < argc; count++)
   {
            printf ("%s\n", argv[count]);
   }
How to add logs in android C/C++ files:

#define LOG_TAG XXX   // its the tag u can see in the logcat.
#include  

LOGE("printing log %s,%d",__FILE__,__LINE__);
 

In Android.mk, Add below line :

LOCAL_SHARED_LIBRARIES := \
        libutils          \
How to Launch an activity/application  in android from commandline:
=============================================

commands to launch an application in android:

adb shell am start -a android.intent.action.MAIN -n packageName/.mainActivityName

If I want to launch one application from commandline, what things I need to do:

1)From APK's AndroidManifest.xml,we can identify the main activity.Then we can use above command

2)Another easy way is launch an application using GUI/by clicking the application At the same time take logs using "adb logcat".

ActivityManager(1132): Starting activity: Intent { cmp=com.android.providers.subscribedfeeds/com.android.settings.ManageAccountsSettings }

ActivityManager(1132): Displayed activity  com.android.providers.subscribedfeeds/com.android.settings.ManageAccountsSettings :500 ms


 we can launch this activity from commandline as below:

 adb shell am start -a android.intent.action.MAIN -n 
com.android.providers.subscribedfeeds/com.android.settings.ManageAccountsSettings
 

How to know the services currently running in Android:

     To list the running services in android

  •   Menu->Setting->Applications->Running Services 

How to mount usb in Linux:

Mount USB if there is no other way in case of embedded linux:

 
  1) insert USB
  2) give "fdisk -l" [lists the /dev/sda1 or sda5]
  3)  mount /dev/sda1 /mnt/ [mount usb,USB file contents will be available in /mnt/ folder]



  4) cp ts.txt /mnt/   #  copy files to usb 
  5) cp /mnt/ts.txt .     #copy files from usb to current folder
  6) sync #Flush buffer read/write contents
  6) umount /mnt/  #unmount usb


Tar/Untar commands in Linux:
=====================


Compress tar.gz file:
# tar -zcvf archiveName.tar.gz directoryToCompress

To decompress an archive use the following syntax:

# tar -zxvf archiveName.tar.gz

Tuesday, October 02, 2012


How to get logcat from the android device which is having IP address:

we can connect to the device with IP address by adb command.
If we are runnign the below command from system,

adb connect 10.1.20.100 #will makes the system to connect with device.

Afterwards if we are giving “adb logcat”, this will prints the logs in your system.So with adb command, we can connect to any emulator or device which is having IP address. It is possible that we can connect to any remote device and can take logs from another remote place.


Starting and stopping Android core services:

Any android core services can be started and stopped by settting properties of a core service. Application can start or stop the any service by below commands:

setprop ctl.stop serviceName
setprop ctl.start serviceName

setprop ctl.stop dhcpcd_eth0 #This will stop the dhcpcd_eth0 service
setprop ctl.start dhcpcd_eth0 #This will start the dhcpcd_eth0 service

From our system, we can communicate emulator or actual device and we can see the properties set by below commands:

>adb shell
$getprop
This will gives/lists  output of all the properties set...


How to compile ICS code in Ubuntu 12.04 64 bit OS?
In  Ubuntu 12.04 64 bit OS, while compiling android ICS code[thru make], it will give FORTIFY_SOURCE error as below:
 + FORTIFY_SOURCE error ... :0:0: warning: "_FORTIFY_SOURCE" redefined 
 Problem for this issue:
 ICS is trying to compile with gcc-4.6. ICS code is compilable in gcc-4.4 only. 
Resolution: 
While giving make{compiling android code}, we can mention the make file to use gcc-4.4 by below commands:
 make CC=gcc-4.4 CXX=g++-4.4 
or 
  export CC=gcc-4.4 CXX=g++-4.4
  make #This will use exported CC & CXX flag's value gcc/g++-4.4 version 

Use below steps to install sun-java6-jdk in Ubuntu 12.04 LTS:

sudo add-apt-repository ppa:flexiondotorg/java 
sudo apt-get update
sudo apt-get install sun-java6-jdk

Monday, September 24, 2012


Configure NFS server:
 
   Set up NFS server linux machine:
   
    NFS server machine ip address is 10.1.10.100
 we have to configure /etc/export entry as follows in NFS server machine:

root@sundar:~# cat /etc/exports | grep "/u"
/u       10.1.10.20(rw,sync,no_subtree_check)


NFS client machine [10.1.10.20] can access the NFS server's u folder with read write access:

/u       10.1.10.20(rw,sync,no_subtree_check)

   

To mount NFS in NFS client:

root@sundar:~# mount -v -t nfs 10.1.19.100:/u /mnt
mount.nfs: timeout set for Mon Sep 24 12:37:05 2012
mount.nfs: text-based options: 'addr=10.1.10.100'
10.1.10.100:/u on /mnt type nfs (rw)
++++++++++++++
 afterwards copy using
cp /mnt/file destPath

Current /etc/export entry:

+++++++++++
root@sundar:~# cat /etc/exports | grep "/u"
/u       10.1.10.20(rw,sync,no_subtree_check)
+++++++++++



In Embedded linux device, How to copy files ? Thru teraterm or NFS or via USB cable or via USB storage.
we can mount the storage, copy the files from USB and copy it to device

Create mount point:

i)Insert USB storage
ii)cd mnt
iii)cd usb [or any folder]
iv) fdisk -l - fdisk commandline tool is managing hard disk/usb partitions in linux
fdisk -l
  list all the partitions
   /dev/sda
   /dev/sda5
v) mount /dev/sda5 /mnt/usb
vi) cp /mnt/usb/file . #Do operations...
vii)umount /mnt/usb #unmount the USB


In linux, How to sort the files by modified date?
I want to list the recently modified files should be listed in top.
The files which is not accessed for long time should be listed in bottom.
Can we write script ? No Need:

we can simply use "ls" command advanced version.

we have to use below command to list the files by recently modified date order.

ls -ult

Wednesday, September 19, 2012


How to run program in server even though our login session is over?

Usually  most people run android source code building from server via putty.
whenever we are giving build or any commands, it will not be executed once the putty session is over.

To avoid this, Linux has one most powerful command. That is screen.

we can use this screen command for various purposes.

screen syntax:
screen commandToBeExecuted


One more beauty of screen command is we can run our application and command in server, we can close the putty session. when we are reopening the putty session,
we can reattach that screen command & get results in ur putty.

For example while building I am getting some errors. One of my colleague is very well known how to resolve that error.Then I will go to his place and give "screen make" command(make is to build android code) while getting errors I will ask him to resolve it. when error is resolved, I can do "screen make" from his system. After this we will get build logs in his system.Not to disturb my colleague's work, I can detach the session from server, But still compilation will be done in background.I can go back to my seat and reattach the session, now the build process logs will be shown in my system.

To summarize:

From my friend's system I will do the following:

To build android code in server, I will give

screen make and will press ctrl+a and d then screen will print some id

  detached from 2309_pts-2

From my system, I will do the following:
  1) will open new putty session
  2) type "screen -r 2309_pts-2" [reattach the session]

Now the build logs will be shown in my system.


This screen command can be used for
  1) building the code even though the client session is over
  2) any background tasks activities can be done through it
  3) any big file downloads/android source code downloads can be done through it
     [In google chrome, there is an option called downloading the file in background even though the browser session is over]
4) To download android source code in background, i will do "screen repo sync", it will download the code in screen session


To list all the screen commands running in a server/system, we can use "screen -ls" command to list all the screen sessions running.




Friday, August 31, 2012


Background Process, Linux:

  if we want to run the process as background,we have to use & symbol.

   bash>./test.sh to run it as foreground service.

 To run it in background,

   bash>./test.sh &

How to run the process as service in linux: [Always up]:

  1) while linux system is in init process, shell files available in /etc/init.d got executed

whenever the system is up,  .profilerc or .bashrc or /etc/init.d/ scripts are executed.
Add your process to run in background

 add below line in your .bashrc or in any /etc/init.d/*.sh scripts
 
  ./MyService &


In Linux, From command prompt, if I want to do some bulk copy,usually I do like this:

 i) in one command prompt, I will perform copy operation
 ii)In another command prompt, I will do other work

We can do the same thing in single command prompt... How to do it ?

 i) run copy operation in background operation
 ii) Continue your work

  >cp bigFolder folderB &
   it will immediately returns to prompt,since copy operation is performed in background.
Next line, I can do any operation.
  >

 Once the copy operation is done, It will show below message in command prompt:

 2+1 cp Done.

 

If we want to mount any folder as sdcard in android device, then we need to look for vold scripts in android


To copy the files to embedded device from Desktop/Host machine:
1.we can mount NFS folder and we can copy from NFS
2.ADB- thru ADB push the files
3.Connect Desktop & embedded device through USB, mount the USB and copy the files through USB

Friday, August 24, 2012



Software Testing:

1.Everything is better if you make your tests before you implement the features

Known testing tools are there.
QTP, LoadRunner, TestRunner

TestRunner which is based on JUnit testing framework.It is used in android CTS testcase. CTS is using XML file for configuring testcases/testcase sequence. Junit is nothing Java testcases.

Ant is a opensource tool to automate the building process. It will use XML to build.
It is similar to make .(make file).

     Android Application project creation & building without eclipse can be automated using Ant tool.


Junit reference:
http://pub.admc.com/howtos/junit3x/intro-chapt.html

Using Ant to build android application project reference:
http://developer.android.com/tools/building/building-cmdline.html
http://www.androidengineer.com/2010/06/using-ant-to-automate-building-android.html

2.Monkey runner tool -Python based module which can control the device complete.
3.Monkey tool- UI/Application excerciser which can generate touch events random generator
which can be used for UI stress tool

4.Software testing books;
  i)Testing computer software
  ii) Lessons learned software testing
  iii)Automated testing -Introduction management and performance

5.Android CTS result
   Android CTS result xml has 3 states.
 
   i)Passed Testcases
   ii)Failed Testcases
   iii)NotExecuted testcases

   Testcases are listed under "NotExecuted" if it is not executed. This can happen only when Virtual machine is crashed and CTS testsuite is not able to proceed further testcases.

 Assume we have 10 testcases.First 3 testcases are passed. while running 4th testcase java virtual machine is crashed.Then CTS tool wont be able to communicate with the VM, so CTS result xml will list as follows:

  Passed testcases:3
  Failed testcases:0
  Not Executed    :7
 
 
6.Teraterm

  Kermit- can be used for bootstrap.supports transfer of text and binary file over serial communication
  X modem -file transfer protocol with Cyclic redundancy check
  Y modem -  allows multiple batch file transfer

7.JFFS2- support for NAND flash devices
  UBIFS- successor to JFFS2, it supports write caching.
      performs better when large raw flash NAND devices,Directory contents are using B+ trees.

8.Android camera:

Android camera HAL module is available in Camera.default.so library.

 Android camera module has 4 components:
   i)Camera client
   ii)Camera service
   iii)Camera HAL module
   iv) Camera driver
  Camera client talks to the cameraservice.Cameraservice talks to camera HAL module.
Camera HAL module talks to camera driver.

reference:
http://marakana.com/static/courseware/android/Aptina-Android-Camera-Internals.pdf

9. Three Components of android adb:
   1.adb server [running on Desktop machine, adb start-server, adb kill-server to start and kill adb server, it is also called as adb host daemon]
   2.adb client [running on Desktop machine, adb logcat ]
   3.adb daemon [running on Android device which will receives data through ports from adb server, can also be mentioned as adb target daemon]
     
10. JDB which can be used to debug android applications



Wednesday, August 22, 2012


Problem solving steps:
========================
1.Log effort on what I am doing for every half an hour or 1 hour work
2.Why we are struck up with problem ?

  i) we dont know what is the problem/what we are doing/why we are doing ?
  ii) Simply try to debug the problem
         Conceptualize the problem
  iii)No clarity on what we are doing, we will do the same thing again and again

3)For every half an hour or 1 hour, Think for 10 mins on what you are upto and what you are going to do?
4)Identify the possible set of problems and localize it one by one
5)For clarity, document what are all the possible approaches tried/why it is failed ?
6)Always start from the known things.[ our task is not do well things we dont know before.To solve
problems, in front of us right now...] It will also lead to know unknown things

7)Anyone can work on known things...
    Knowledge
     I know that I know - 3 %
     I Know that I dont know=2%
     I dont know that I dont know -Unleashing this knowledge /handle this type of scenario unleashes your potential.


What to do if CTS tool is not detecting the android device but adb is detecting a device?

Sometimes if we have done any changes not compliant to android, then this problem will happen.

1) if the CTS tool is not detecting the andorid device, we need to check the
platform/tools/tradefederation source code. This is having DeviceStateMonitor module.

2) By running cts-tradefed, it will saves the logs in tmp/log_xxx.txt. we can check error logs
from here and match the platform/tools/tradefederation source code.

running cts-tradefed,
we will get CTS prompt.

cts-tf>list devices

list devices will give device and its state.

Device states are available,Unavailable and allocated.

Allocated state -Allocated state device is currently running tests.
Available state- Device is available CTS is able to detect the device
Unavailable state- Device can be

    To check "available" state, waitForDeviceAvailable() will be called from DeviceStateMonitor.java.

WaitForDeviceAvailable()
{
// A device is currently considered "available" if and only if three events are true:
        // 1. Device is online aka visible via DDMS/adb
        // 2. Device's package manager is responsive
        // 3. Device's external storage is mounted
        //

}

 waitForDeviceAvailable() function will be varying for every android version.

Tuesday, August 21, 2012


I)What is CTS ?
II)CTS components
III)How to Run CTS from end user level?
IV)How to run CTS from Windows?
V)CTS binaries and source code structure


I)Why we need CTS ?
 
CTS testcases tests whether any android apis are modified or any changes done in android that is not compliant to android standard.
Google approves binary only when all CTS testcases are successful. For google approval process,
CTS test cases are executed on device and output .xml is sent to google team.

They will also run the CTS testcases from their end. If there is no failure, then they will approve the binary for the release.
Most of the Mobile operators will expect that the binary should be approved by google.

For some failure cases, we can get a waiver from google. For example, if it is a android DTV/Setupbox, then there wont be any GPS device in it.So all the GPS testcases will fail or not applicable for that device. Waiver request should be reasonable.

II) CTS components:
    CTS is an automated testing application that includes two major components
 1)CTS test application runs on desktop & manages test execution]
 2)Junit testcases running on Mobile or emulator or android device
  JUnit testcases are written in Java and packaged in Android.apk files to run on target device[emulator or android device].
 
III)How to run CTS from end user level?
   1.CTS can be run from Source code in linux
     
 if we have android source code, android/CTS folder will be there.
 we can compile CTS by following steps

 source build/envsetup.sh
 lunch sdk-eng
 make cts 

 Once the compilation is over, we can run
 >cts-tradefed 
 from command line.
 From cts-tradefed it will gives cts prompt.In cts prompt,
 type "list devices" to list the connected devices/emulator.You can refer the android cts document for    more information on list of commands.

 [cts-tradefed binary will be available in out/host/linux-x86/bin/cts/android-cts/tools/]
 cts-tradefed is a script file to run JUnit testcases.

     
   2.CTS can be run from downloaded binary  
         we have to download android compatiblity test suite from android site.

we have to configure this folder in PATH variable
and then we can run
 cts-tradefed in commandline.
     

 IV)How to run CTS from Windows ? Is it possible ?
      It is possible to run CTS from windows.
 Reason:
 "JUnit testcases are written in Java and packaged in Android.apk files to run on target device" from android cts manual.

 cts-tradefed is a script which will configures java to run Junit testcases.

 Configure CTS in Windows OS:

 Step1: adb path should be configured in PATH variable and "adb devices" should list down the devices.
 Step 2:
    cts-tradefed script will contains the following lines:


CTS_ROOT=${ANDROID_BUILD_TOP}/out/host/${OS}/cts
    JAR_DIR=${CTS_ROOT}/android-cts/tools
JARS="ddmlib-prebuilt.jar tradefed-prebuilt.jar hosttestlib.jar cts-tradefed.jar"

for JAR in $JARS; do
checkFile ${JAR_DIR}/${JAR}
JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}
done

   java -cp ${JAR_PATH} -DCTS_ROOT=${CTS_ROOT} com.android.cts.tradefed.command.CtsConsole

Assume that I have downloaded "android-cts-4.0.3_r3-linux_x86-arm.zip"  and unzipped it

My folder structure will be as follows:D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts\tools
The simplification of this script is as follows for windows:

java -Xmx512M -cp D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts\tools\cts-tradefed.jar;D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts\tools\hosttestlib.jar;D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts\tools\ddmlib-prebuilt.jar;D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts\tools\tradefed-prebuilt.jar -DCTS_ROOT=D:\android-cts-4.0.3_r3-linux_x86-arm\   com.android.cts.tradefed.command.CtsConsole

run this command in commandline then you will get cts prompt in windows OS too.

-cp is the class search path for the zip or jar files. whenever some class is encountered in jar file,java will look for it in class search path.
CTS_ROOT will be used internally in jar files, so we are setting CTS_ROOT by -DCTS_ROOT.
CTS_ROOT is D:\android-cts-4.0.3_r3-linux_x86-arm. not a D:\android-cts-4.0.3_r3-linux_x86-arm\android-cts.[by giving this, i got errors]


V) CTS Binaries & source code structure:
          1)cts-tradefed.jar source code path is "android_source_path/cts"
 2)hosttestlib.jar
 3)Junit.tar
          4)ddmlib-prebuilt.jar
          5)tradefed-prebuilt.jar

 ddmlib-prebuilt.jar and tradefed-prebuilt.jar is available as prebuilt binaries. No source code available

 tradefed-prebuilt.jar is a CTS component runs on Desktop machine and manages test execution. platform/tools/tradefederation is the source code folder path for tradefed-prebuilt.jar file.














     

Saturday, August 18, 2012





MPEG TS:

1)  MPEG TS file has multiple elementary [multiple audio track] streams... why ? what is the purpose of it?
I got lost once I got the info like TS can have multiple Program streams what is the purpose of it ???

Transport Stream had been originally designed for broadcast.
to carry several media over one bit stream, all the streams are muxed in to one stream and sent it over the network.
Consider DVB (digital TV): each transponder (= frequency) provides one bit stream. But you already need at least two streams for a TV channel: audio and video. And then a lot more that you'll never see carrying meta-information. So instead of transporting each of these streams on a separate frequency, they are multiplexed into one bit stream. That is the MPEG-TS (Transport Stream). A demuxer then takes this stream and separates it into substreams which carry the real information.
As to which audio stream is played: a TV channel can have several audio streams (for example, normal audio, audio with descriptions for visual impaired, another language, etc.). By default, a player will probably play the first audio stream but can switch audio streams at any time.

 TS can have multiple elementary streams which will have separate streams for video/audio/subtitle/Program timing information.


while we are using airtel/Tata sky SetTopBox, we can see the program information at what time, what is the program. This kind of information
is available in PSI of MPEG TS format.PSI means Program Specific Information. PSI contains information about @ what time and date,
what program is to be played.

For more:http://en.wikipedia.org/wiki/Program-specific_information


2)Seek functionality for MPEG TS:

If we want to add seek functionality to MPEG TS what should we need to do?

   MPEG TS fileformat is not designed for random access. So It can be viewed sequentially.
Android stagefright doesnt have a seek functionality for TS file formats.
But VLC player has added seek functionality in TS fileformat based on PCR [Program clock Reference].

3)what is PCR :

To enable a decoder to present synchronized content, such as audio tracks matching the associated video, at least once each 100 ms a Program Clock Reference, or PCR is transmitted in the adaptation field of an MPEG-2 transport stream packet.
Decoder will calculate actual system time clock.

The PCR is a clock that represents 27 Mhz clock at the encoder side. Hence each tick of PCR clock represents the 1/27 Microseconds.

The first step is to be able to parse the PCR packet. The PCR ticks are maintained by a specific PID (mostly video but can be audio or alternative packets). When the PCR is present in the packet, it is of Adaptation field, type 2 or 3. You can refer to this or wiki for understanding how to parse PCR.

Once you get the PCR value of the packet - (use a 64 bit integer) you have a timestamp P0 for that packet. Now you can seek to exactly say 10 seconds, when you get next PCR packet, with a time stamp, P1 where

P1 = P0 + 10 * 27 * 10^6

So when you see another such packet containing timestamp P1 or more you can be sure of elapsing 10 seconds.PCR may find discontinuity hence, more calculation is needed at the point PCR base shifts.


From :http://stackoverflow.com/questions/6443615/pcr-based-seek-for-mpegtsfile

4)How to generate PTS[Presentation Timestamp] from PCR ?

PCR has 33+9 bits, the PTS 33 bits. The 33 bit-portion (called PCR_base) runs at 90kHz, as does the PTS. The remaining 9 bits are called PCR_ext and run at 27MHz.
 there should be a time-offset between the PTSs of the multiplexed streams and the PCR, it's usually in the range of a few hundred ms, depending on the stream.

The respective decoder needs some time to decode the data and get it ready for presentation at the time given by the respective PTS, that's why the PTSs are always "ahead" of the PCR. ISO-13818 and some DVB specs give specifics about buffering and (de)multiplexing.

From: http://stackoverflow.com/questions/6199940/generate-pcr-from-pts


5)MPEG2 TS:
Transport Stream had been originally designed for broadcast. Later it was adapted for usage with digital video cameras, recorders and players by adding a 4-byte timecode (TC) to standard 188-byte packets, which resulted in a 192-byte packet.This is what is informally called M2TS stream.
It is used in Bluray disc  and digital video cameras.

Timecode allows quick access to the any part of the stream either from a mediaplayer or from a non-linear video editing system.


6) SetTop Box:
    i)local cable operators give cable connection that is DVB-C signal
    ii)Tata sky or Airtel digital - we have to fix antenna to receive signal- this is called DVB-S (DVB-Satellite signal standard)

7)IPTV
Internet Protocol television (IPTV) is a system through which television services are delivered using the Internet protocol suite over a packet-switched network such as the Internet, instead of being delivered through traditional terrestrial, satellite signal, and cable television formats.    

 IPTV provides  3 main services:
   i) Live TV-with or without interactivity related to the current TV show;
   ii) time-shifted television: catch-up TV (replays a TV show that was broadcast hours or days ago), start-over TV (replays the current TV show from its beginning);
   iii)video on demand (VOD): browse a catalog of videos, not related to TV programming

http://en.wikipedia.org/wiki/IPTV

8) SD or HD TV
  High Definition (HD) is swiftly replacing Standard Definition (SD) when it comes to television broadcasts. HD has a high picture resolution of 1920x1080, with 2.07million+ pixels offering 5 times more detail than SD. It has a wide aspect ratio of 16:9 better suited for our eyes which have more horizontal than vertical span, as compared to an aspect ratio of 4:3 in SD.

9) what is Trick Play:
       -Ability to receive broadcast television shows with VCR-like functions such as pause, rewind, fast forward, replay and skip, collectively known as 'trick play', all while rendering a live video stream.


 
 

Friday, August 17, 2012


Problems faced while installing android application setup:

1.First time I have opened Android sample application, I got like "Android Native supported libraries"
need to be installed. I installed Android native libraries

2.In 64 bit Windows 7, I faced this problem:
 Android SDK installer [ installer_r08-windows.exe] is not detecting JDK.

I tried the following:
  i)Set the JDK bin/ JRE Bin in PATH variable, it is not working
  ii)Android SDK installation dialog shown that JDK folder path to be set in JAVA_HOME variable
   I did that it is also not working.
solution:
  1) Copied java.exe and javaw.exe from JDK bin to c:\windows\system32 and  c:\windows\sysWOW64
 Now android sdk setup is detecting JDK.

Following steps  are needed for ICS Android application Development Setup :

1.Downloaded the JDK7 and installed it in machine
2.Downloaded installer_r20.0.3-windows.exe from google site
3.Run the "installer_r20.0.3-windows.exe"
4.Followed the below blog to download ICS SDK
http://www.android.pk/blog/tutorials/install-and-run-android-4-0-sdk-and-ice-cream-sandwich-on-pc/
Now ICS SDKs are installed.Create the AVD for for any platform which requires for application development
5.Downloaded ADT plugin from google site
6.Downloaded the Eclipse classic
7.Downloaded the android_sdk_for_windows.zip and set the tools/platform-tools  folder in PATH variable
8.Installed & Opened the Eclipse classic application
9.In Eclipse, Select    Install new software & select the localpath and add the ADT plugin zip file &
install the files
10.After the ADT plugin was installed, eclipse showed that it requires android support libraries...I installed that android support libraries too...


11.In eclipse->Preferences->Android->SDK location as "android_sdk_windows" folder path.
12.create new android application in eclipse
13.To run the application in emulator,
In Eclipse, Select Run->Run Configurations->Give Some string in "Name" box and select Launch default activity.
 In "Target" tab,select the AVD configuration to run the application





Thursday, August 16, 2012


Hyderabad is famous for following things:
1.Biryani [Hyderabadi biryani]
2.Irani chai
3.Pearls
4.Haleem [paste kind of food made of mutton meat]


Things learnt today:

1.Chrome browser is having to HTML5 support.
2.what is USB modem stack?
    USB modem client is installed in mobile/device. USB Host driver is installed in laptop or system.
with the help of USB modem stack we can take mobile's internet connection to laptop or system.
In android, this is called tethering.

3.Wifi Hotspot in android mobiles:
    Android mobiles are having Wifi hotspot support. if mobile has internet connectivity, our mobile will acts like WiFi router . we can connect device or laptop
to that WiFi hotspot.
   To provide support WiFi hotspot, WiFi chip should be available in android /mobile device.
Accessing internet via Wifi hotspot is also called as WiFi tethering.

4.VoIP phone:
A VoIP phone uses voice over IP (VoIP) technologies allowing telephone calls to be made over an IP network such as the Internet instead of the ordinary PSTN system. Calls can traverse the Internet, or a private IP network such as that of a company. The phones use control protocols such as Session Initiation Protocol (SIP), Skinny Client Control Protocol (SCCP) or one of various proprietary protocols such as that used by Skype.
From : http://en.wikipedia.org/wiki/VoIP_phone

Wednesday, August 15, 2012

In Embedded system, First we need to flash loader & then we need to install boot loader (U-BOOT).UBOOT  will configure the kernel  (also pass kernel arguments).


1. what is loader ?
A loader is the part of an operating system that is responsible for loading programs. It is one of the essential stages in the process of starting a program, as it places programs into memory and prepares them for execution. Loading a program involves reading the contents of executable file, the file containing the program text, into memory, and then carrying out other required preparatory tasks to prepare the executable for running. Once loading is complete, the operating system starts the program by passing control to the loaded program code.

2.why we are doing NAND ERASE/NAND WRITE commands for writing loader/U-BOOT/kernel in embedded linux?

In Embedded linux/devices, bootloader is flashed into flash memory.To write kernel/bootloader into flash memory, we
are using NAND ERASE/WRITE.NAND ERASE/WRITE are the commands to reprogram the ROM chips.


Flash memory is a non-volatile computer storage chip that can be electrically erased and reprogrammed. It was developed from EEPROM
(electrically erasable programmable read-only memory) and must be erased in fairly large blocks before these can be rewritten with new data.
The high density NAND type must also be programmed and read in (smaller) blocks, or pages,
while the NOR type allows a single machine word (byte) to be written or read independently.

Example for Flash memory: ROM, EPROM,EEPROM
Wiki:http://en.wikipedia.org/wiki/Flash_memory


3.what is Samba file system ?
   In windows, we can access the shared folder in a network. But in linux, if we want to share the folder across the network, we need to install the samba.
So that from any machine in the network, we can access the files as like local folder.

4.In Embedded system, First we need to flash loader & then we need to install boot loader (U-BOOT).UBOOT  will configure the kernel  (also pass kernel arguments).

5.we can use U-Boot to load kernel or other file from TFTP into RAM
6.tftp in embedded linux:
   For transfering the kernel/long files to embedded device,we can use
                 i)tftp
ii) serial port access
        But tftp will give faster data transfer of files. Reason is that tftp acts on ethernet/network.Ethernet gives 10 Mbps data transfer speed.
 Maximum data transfer in Serial port is 128Kbps or 192 kbps.
But tftp needs
          i) IP configuration [Ethernet hardware]
          ii)tftp client

7. NFS  [Network file system]:

Network file system will boot system files/libraries from the server. NFS client wont have any libraries.
It will just load the required system files/libraries from server.

  NFS use in Embedded system:
         i)In embedded system, instead of flashing binary every time to embedded device, we can just configure the development system's compiled library path in embedded device.
For every compilation, libraries got updated and embedded device will boot libraries everytime from development system.

  Things needed for accessing NFS:
    i) Ethernet[hardware for IP address]
    ii) NFS client

8. ADB CONNECT
    If we want to get logs from android mobile/consumer device, what we can do ?

   i)we can connect the android mobile consumer device to system via USB and we can get logs via "adb logcat".
   ii) For android development, if we are using putty from windows system to access the Linux server which has source code.
But my device is connected to windows system. In such a scenario, we are able to take android logs from Linux server or windows system.
(But the android device should have IP address.)
How it is possible ?

  if the android consumer device is having IP address[ethernet support],we can connect to the device via IP address
          "adb connect android_device_ipaddress" can be used to connect to android device.Next if we are putting logs,we can get logs via adb logcat.

9.Embedded linux boot sequence:
   ROM Code -> BootStrap/Loader -> U Boot -> Kernel -> RootFiles








Tuesday, August 14, 2012


What the Jumper settings will do ?
 Jumper is used to make short circuites between two or more pins.
One of the real usage is Primary and secondary hard disk is configured via jumper settings.


How CPU usage is calculated ?
1.Assume if the CPU speed is 1KHz then it will executes 1000 cycles/second [/read 1000 bits per second]
   
  If we are doing program which requires 500 cycles/ second means then CPU usage is 50%. Rest of the 50 % can be used for other
process or program.
 
  if the program is more intensive and takes 1000 cycles/second to execute, then no more process can run that time. So CPU is so busy in executing the program.
For any external event/program it will respond slowly.

 Normally CPU speed is measured in GHz nowadays.

1KHz = 1000 Hz
1MHz = 1000 KHz
1GHz = 1000 MHz

Sunday, August 12, 2012

indian companies in jeans/shirts/pants

List of indian companies in jeans product:

Indian companies in jeans:

1.Flying machine
2.Shoppers stop
3.Mufti -available in shoppers stop,central,westside, globus
- available in Shoppers stop
- range from Rs 1000
4.New Port -Arvind mills india
5.Excalibur- Arvind mills india
6.integriti jeans
7.Spykar jeans
8.Numero uno
9.K-Lounge
10.lawman pg3
11.Bare denim -Pantaloon group
12.Killer jeans - kewal clothing ltd
13.Trigger jeans
14. DJ & C jeans [from Big Bazaar]

Indian companies in Shirts & Pants:
1.Blackberry's
2.Indian terrain[From chennai]
3.Raymond
4.Zodiac
5.Grasim
6.Qwalior
7.Color Plus [is from Raymond]
8.Pantaloon[their own brand clothes mostly]
9.Shoppers Stop [their own brand clothes mostly]
10.globus


if you know any indian company in shirts/jeans business, Please replay
& add it too.

Thursday, August 02, 2012


Why YUV format is used in MPEG2/MPEG4/H264encoders for compression ?

  MPEG2/MPEG4/H264 is lossy compression.
RGGB will have image details/color information in all the RGB represented bytes.
if we are applying for lossy compression, there is a chance for losing bits information.
if LSB bits are affected there wont be a big change in image. If MSB bits of RGB is lost,
this will be bigger change in image and user can perceive/can observe the changes in image.

  In YUV format, image details will be available in Y data[ this will have monochrome/ black and white image]. U and V component is used to store color information.

  Eyes can't perceive color information changes than image information. But it can easily observe the changes in image information[Y data which will have black/white image]. So In lossy compression, encoders wont disturb the image information & will
disturb or compress more in color information [UV components]

     If we are using RGB, we cannot separate image information & color information.Because all the pixels will have the image information and color information.

This is the reason why we are using YUV format in lossy compression or MPEG2/MPEG4/H264 encoders.


   

Friday, July 27, 2012

Dalvik Debug Monitoring System:



DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.
  • From Eclipse: Click Window > Open Perspective > Other... > DDMS.
  • From the command line: Type ddms (or ./ddms on Mac/Linux) from thetools/ directory

    How DDMS Interacts with a Debugger

    When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol

    DDMS features summary:/when we will use DDMS ?
    For the following purpose, we can use DDMS.
    1.Viewing heap usage for a process
    2.Tracking memory allocation of objects
    3.Working with emulator or device's file system 
        we can copy video files/files to emulator or device with DDMS
    4.using logcat : logs can be viewed and filtered based on LOG_TAGS
    5.monitoring network traffic information






Changes/Features in android  Icecream sandwich:

1.RTSP streaming was integrated with NuPlayer
2.Valgrind  static memory leak tool is ported to android
3.gdb is ported to android
4.OpenCV image processing library is ported to android that is why facedetection / recognition is possible in
ICS . Samsung S III ICS is having face detection functionality
5.OpenAL application layer support  [refer system/media/wilhelm folder path]
6.Subtitle support through TimedTextPlayer for video/audio playback
7.ION memmory manager support in ICS
[ ION is a generalized memory manager that Google introduced in the Android 4.0 ICS (Ice Cream Sandwich) release to address the issue of fragmented memory management interfaces across different Android devices. There are at least three, probably more, PMEM-like interfaces. On Android devices using NVIDIA Tegra, there is "NVMAP"; on Android devices using TI OMAP, there is "CMEM"; and on Android devices using Qualcomm MSM, there is "PMEM" . All three SoC vendors are in the process of switching to ION].
More about ION memory can be found : http://lwn.net/Articles/480055/
8.Framework for DRM
9.NuPlayer is introduced for HTTP live streaming in Honeycomb tablet. In ICS,  RTSP stack/streaming is removed from stagefright and integrated into NuPlayer
10. There are two ways to integrate the decoders in gingerbread
        i) Software decoder path [google decoders are integrated by deriving from MediaSource.InstantiateSoftwareDecoder() function is used within OMXCodec.
        ii) OMX path
       
  From ICS onwards, Google decoders are integrated in OMX Path and InstantiateSoftwareDecoder() is removed in stagefright




How will you identify the memory leaks in android ?
1.We can use valgrind tool to find memory leaks, stack corruption, array bound overflows etc
2 Valgrind tool is ported in Icecream sandwich onwards
3.From DDMS, we can select the process and start profiling, we have to do suspected memory leak operation,some file will be created.we can use eclipse memory analyzer tool to identify the memory leaks from this file
4.We can identify the memory leak by process. By putting ps command it will list down the memory occupied by process. Same can be viewed in settings option also. 


      If we want to check whether the video playback has memory leak or not,we have to type ps command to identify the memory occupied by mediaserver process. we can run the video continuously for 100 times or 200 times. Afterwards we have to check memory again for mediaserver process in ps command. if there is a great increase in memory, then we can confirm there is a memoryleak in a video playback. 


What is missing in Android Stagefright/NuPlayer RTSP streaming ?

1.Jitter buffer handling
2.RTCP handling
3.Error correction and feedback through RTCP Sender report/receiver report

What are all the buffering mechanism available in OMX ?
   1.AllocateBuffer - Allocates buffer
   2.UseBuffer - use the buffer given by the downstream component. Example using the video renderer's memory to fill the decoded data

When the input buffer or output buffer of the component should be released?
        Once the OMX input buffer is used and ready to release,  it will return the EMPTY_BUFFER_DONE event to the stagefright or who is owning the buffer. Once the IL client received the EMPTY_BUFFER_DONE event, it can release the input buffer.
     OMX  IL client will receives the FILL_BUFFER_DONE event from OMX component once the output buffer is used and ready to release. Once IL client received the FILL_BUFFER_DONE event, IL client will frees the output buffer.

How Seek operation is executed in Stagefright ?
        Once the application is giving seek, Thru stagefright player, awesome player calls the seek() function.

How seek operation is notified to the parser or Extractor ?
     within Awesomeplayer, SeekTo() fn is called, it will sets the ReadOptions structure values as seek mode set and seek timestamp is also stored in this structure.

     Awesomeplayer while calling decoder, it will  invoke decoder as below

            mVideoSource->read(&decodedBuffer, &readOptions);

This readoptions value is passed to decoder and decoder will have the pointer to the MPEG4/MKV extractor's media source.
       Decoder will invoke read() fn of the audio/video source of the extractor by passing readOptions.

within parser's media source ->read() fn, it will checks whether the seek mode is set or not. if it is set, it will
do seek to seektimestamp through parser.


                 

         

 

     

Wednesday, July 25, 2012

what is OMX Content Pipe  ?

From OMX IL 1.1 standard, we can integrate source[3GP parsers] or Streaming source /sink [MP4 muxer].

Through content pipe, it is possible for us to integrate the source/sink components.

Content Pipe specification explains on how it open/read/write positions from storage/ from network.

Friday, May 18, 2012

STL & GNU C++ with codeblocks

If we are using STL program in codeblocks, we have to enable GNU c++ option
by selecting

Project->Build options->Have g++ follow the coming C++ 0x ISO C++
language standard [-std =c++0x]

Otherwise it wont compile in codeblocks editor. while submitting the
same code in codeforces.com, we have to select
GNU C++0x4 option for uploading the cpp file.

BHTML & BCSS codeforces problem log

BHTML & BCSS codeforces problem log:

What are all the steps I have done to solve this problem:


For a problem, I started by generating the strings and tried to
compare the strings as follows:

<a><b><b></b></b></a>

Generated string [from HTML] is as follows:
a
a b
a b b

pattern a b has occurence as 2 times.

Pattern should be there in the generated string.

we need to check all the patterns and count/increment the current occurence.

This approach is taking more time, I got "timeout exceeded".

Once again I got failed in substring test case.

for example, <sundar/>
for pattern :sun it should return 0. But it is returning some other values
I stored the values in hashtable and added the number in an array.
instead of comparing strings, I started comparing
integer values.



1)timeout exceeded
2)substring testcase failure <sundar/> query:sun but output is 1. it should be 0
3)string comparison takes time, I added the string in hashtable and
generated the int array to compare & reduce
time
4) Integer comparison also takes around 7 seconds for a problem &
failed in somecases giving improper output.
5) I checked the case of seulgi kim's code. Based on my understanding,
I have created
Nary trees from the HTML. From Nary trees, we will search for the
given query recursively.

6.Through debugging found that PushToStack should be available for
<tag/> cases too
7.Modified the PreOrder() fn return as Long
8.modified the readQuery() to read char by char
9.deleted the query array and created it for each query
10.Tried by changing the stack size limit.
#pragma comment(linker, "/STACK: 2000000")

11. I doubted the readQuery() but I am getting large size input for the query.
I changed the Maximum Query characters Count[MaxQueryCount] from 250
to 4000. Now I have posted it, it was working fine & accepted in the
codeforces.
I thought like query line will have maximum 250 characters. I haven't
read properly about the problem sentences:

" Each query is a sequence x1, x2, ..., xn, where xi is the i-th
element of the query, and n (1 ≤ n ≤ 200) is the number of elements in
the query. The elements are separated by single spaces. Each query
doesn't begin with and doesn't end with a space. Each query element is
a sequence of lowercase Latin letters with length from 1 to 10."

200[queries] * 10 [tag size]* 199 spaces = 398000 characters it can
be...But since the testcases are having less than this limit, I am
able to run with 4000

12.Eventhough I successfully submitted the code in codeforces, I could
found one more problem... that is allocated nodes are not released
properly. I released all the nodes including parent nodes & resubmitted it...

Monday, May 14, 2012

Competition Sites to practice

1 UVA:http://acm.uva.es/p - The Valladolid University Online Judge.
Over N problems, for a reasonable value of N. The problems are culled
from old contests, and online contests.
2.ZJU:Zhejiang University Online Judge - http://acm.zju.edu.cn
3.SGU:Saratov State University Online Contester - http://acm.sgu.ru
4.PKU: Peking University Judge Online of ACM ICPC -
http://acm.pku.edu.cn/JudgeOnline
5.topcoder
6.codeforces

Wednesday, May 09, 2012

Books recommended in codechef

1. Standard book on Algorithms - Introduction to Algorithms by T H
Cormen, C E Leiserson, R L Rivest, C stein ( Famously known as CLRS )
2. Basic Algorithms - Algorithms by Richard Johnsonbaugh, Marcus Schaefer
3. Game Theory - Winning ways for your mathematical plays by Elwyn R.
Berlekamp, John H. Conway, Richard K. Guy
4. Programming challenges - Steven Skienna
5. Concrete Mathematics - Knuth
6. How to solve it by a computer - Dromey
7. Structure and interpretation of computer programs - Elsevier
8. Programming Language Pragmatics - Micheal Scott : It gives
comparative study of various programming languages and helps you
decide choose the appropriate ones on the basis of time they take to
process information

How P frame seek support will be added in any multimedia framework

Some multimedia frameworks will have support for P frame seek. Some
frameworks wont have this support. So How can we add this support ?

For P frame seek, we can not start directly start decoding & rendering
from the P frame;
Since P frame doesnt have entire frame information, if we start
decoding & rendering from P frame, it will shows
green patches on screen and affect the user experience.


How P frame seek is supported in Directshow multimedia framework ?


For any seek timestamp, Parser will seek the I frame timestamp before
the seek timestamp.
Ex :
I frame is available in 10th second.
if the seek is done to 12th second, the Parser will fetch I frame from
10th second and give it do the decoder.

Source Filter will set IMediaSample's SetPreroll() as true. The
decoder will decode the frame,get necessary information and wont give
it to the renderer.

Once the timestamp reached the seek timestamp, Parser will set the
setPreroll as false, then frame will starts rendering.


OpenCORE:

In OpenCORE's frame have an option to set DoNotRender flag. If we set
this flag, it wont render the given frame.

In Generic, In any multimedia framework,

if we are calling seek to any timestamp, Upto seektimestamp is
reached, video and audio frames are dropped without rendering on
hardware device.In case of audio, we will have more I frames. But if
we are rendering audio alone, video takes more time to catchup
video.User might be able to observe the weird behaviour since ear is
more sensitive than eyes. In this scenario, rendering the audio also
causes the audio clock to increase. It will cause AV sync issues once
video starts rendering.

In any multimedia framework, we have to do the following steps to
do P frame seek:



1.ParserseekTo(Nearest_I_Frame to SeekTimesamp);
2.ParserRead(frame);
3.Decode(decodedAudioVideoFrame);

4. if (decodedAudioVideoFrameTimestamp < SeekTimestamp)
{
release audioVideoFrame;
}
else
render(decodedAudioVideoFrame);

weird video behaviour in Stagefright

In stagefright, if any weird behaviour is observed in video. Following
steps need to be taken:

1.we need to print time taken by parser and decoder.[To check any time
taken process involved]
2.Check any frame is dropped by enabling log [dropping late frame in
awesomeplayer.cpp]
3.Print logs in all sleep() fn in AwesomePlayer[while rendering
frames, threads might go to background and wont do anything because of
Sleep() fn
4.Check for any postVideoEvent(10000ms) this might delay the rendering
of frames. For optimization or any other reason, chipset vendors might
tune this
value

String comparison

Whenever we need to compare strings, what we can use it?

Text: abc bcd bcd abc
Pattern: abc bcd
[Ex: BHTML & BCSS codeforces problem]

we need to compare text and pattern using strcmp. But naive string
comparison takes more time.

Solution 1)we can use RobinKarp or KMP algorithm to reduce time. or
else we can do the following way to avoid the problem.


How to avoid this:

we can use array to store the strings without duplication.

Array [][]={ "abc","bcd"}

Text Array: {0,1,1,0}
Pattern Array: {0,1}

then apply naive comparison in TextArray and pattern Array.

Solution 2)Compare to string array, int array comparison will takes less time.

Solution 3) if we are using array also, we need to compare all the
elements in array on worst case to add or lookup.
in this case, what we can do to improve this ?

We can use Binary Search Tree to store strings. if the given
string is less than the root string,
we need to search it from left child of the string.if it is greater
than or equal to the rootstring, we need to search the
right child of the root.

STL map is using RedBlack tree implementation. we can make
use of map to store strings.STL map can also be used for Hashtable.

Thursday, May 03, 2012

DecodeButDoNotRender

Insights on How to implement DecodeButDoNotRender flag in any
multimedia framework ?
This will happen when we dont have more I frames.

Wednesday, April 25, 2012

what is structure padding ?

what is structure padding ?

if the system is 32 bit system,
we are allocating memory like this:

struct test
{
char a;
int b;
};

It will allocate 8 bytes of memory in 32 bit system. For char,compiler
will allocate the 4 bytes. [char may be 1 or 2 bytes]
this is called data alignment. Data alignment means putting the data
at a memory offset equal to some multiple of the word size,
which increases the system's performance due to the way the CPU handles memory.
For char, 4 bytes are allocated. it will use only 1 bytes.Rest of the
bytes are filled with junk values. this is called structure padding.

For example, in 32 bit system,the data to be read should be at a
memory offset which is some multiple of 4.
if the data starts from the 18th byte, computer has to read two 4
bytes chunks to read the data.
if the data starts from multiple of 4[4,8,12,16,20], computer can read
4 byte chunk once to read the data.
If the read is from two virtual memory pages, then it will take more
time than expected.

In this way, padding improves performance.


if the data members are declared in descending order it will give
minimal wastage of bytes.

struct Test
{
char a;
int b;
char c;
};

sizeof(Test) is 12 bytes.

But if we declared like this, 8 bytes will be allocated for structure "Test".


struct Test
{

int b;
char c;
char a;
};

How to avoid structure paddding?
if we dont want to waste memory & tradeoff the performance,
we need to use pragma pack to align data.

Tuesday, April 24, 2012

How OMX core library is loaded for stagefright by chipset vendor like Qualcomm /Nvidia ?

How OMX core library is loaded for stagefright by chipset vendor like
Qualcomm /Nvidia ?

Qualcomm and NVIDIA processors will have built-in hardware codecs support.
They will provide the OMX components too. Their OMX core will be
loaded from libstagefrighthw.so .
This libstagefrighthw.so library will be loaded by stagefright in
OMXMaster.cpp in

addPlugin("libstagefrighthw.so");

vertical/horizontal sync in video

Video Is Composed of a Series of Still Images.
changing fast enough that it looks like continuous motion.
timing informations are called vertical sync/horizontal sync.

vertical sync - indicates when a new image is starting
horizontal sync -indicates when a new scanline is starting

Each still is composed of series of scanlines.

Interlaced vs Progressive:
For displays that "paint" an image on the screen, such as a CRT,
Interlaced-each image is displayed starting at the top left corner of
the display, moving to the right edge of the display.

Interlacing: First odd number of pixels are sent to display and then
even number of pixels are sent to display the image.
Advantage: we can reduce memory transfered to display by half for every image.

Progressive: pixels are displayed by sequence of lines.For Higher
resolution, we go for progressive.
Interlaced: First half of image is displayed on screen and then next
half of image is displayed

string searching algorithms with code

http://www-igm.univ-mlv.fr/~lecroq/string/string.pdf

Friday, April 20, 2012

code forces FileList problem

Code forces FileList problem :

PseudoCode:
==============

#define MAX_FILENAME 8
#define TwoContinuousDots 0
#define SingleCharBetweenTwoDots 1
#define MAX_FILE_EXT 11
#define EndsWithDot 0
#define MAX_EXT 3


1.read the string input
2.Identify the dot & break the loop
3.if (stringBeginsWith == Dot) return NO;
4.if (CurrentCharPosition > MAX_FILENAME) //DotPosition exceeds
MAX_FILENAME allowed || Dot is not available within 8 character
return NO;
5.Store the ++LastDotPos
6.start loop through the string till EOS reached
7.if [ currentDotPos - lastDotPos == TwoContinuousDots ] { return NO;}
8.if ( CurrentDotPos - lastDotPos == SingleCharBetweenTwoDots ) { return NO;}
9.if ( CurrentDotPos - lastDotPos > MAX_FILE_EXT ) return NO;

At Last of the string,
10.if( CurrentDotPos - lastDotPos == EndsWithDot ) return NO;
11.if( CurrentDotPos - lastDotPos > MAX_EXT ) return NO; //Last
extension exceeds MAXIMUM_EXTENSION size
12.Yes... we are going to parse the valid String
13.create loop1... Search First Dot
14.if (char == FirstDOT) create loop2 and look for SecondDOT
15.if no second DOT and EOS reached,print string. [Ex: t.txt]
16.if(TwoDotsDiff <= MAX_EXT) printf( secondDot + 1 char);Move i by 1
17.else print (3 characters) Move i by 3

Thursday, April 19, 2012

Solve contest problems

To Solve any codeforces contest problems:

1)Prepare the testcases from the given problem statement
2)Prepare test samples
3)Prepare design
4)Check if any datastructure can be used & what will be the cons & pros
5)If multiple datastructure can be used, Identify the best
suitable datastructure
6) Sometimes tradeoff clarity/simplicity over efficiency
7) Once completed the code, test with test samples
8) if anyone has already submitted the problem, we can see the
testcases used for testing the solution.
we can check our code with codeforces simple testinputs
This will clarify if we misunderstood the problem statement.
[Ex: For Cd and PWd commands problem, from the problem
statement, I assumed that .. or / wont come at end.
But from the testsamples,I came to know this as a valid input]
9) Think on how to improve the code

After seeing others code,

1) Prepare testcases from code
2) Prepare testsamples to break the code
3) Randomly remove some lines of code and try to fix it...
This will give a chance to understand/read others code.

4.Identify any language functions/features used in code for
addressing particular scenarion & think of it
how to use it
5.Check the efficient code[less execution time] written by others
6.Check others code which is having clarity and simplicity

Tuesday, April 17, 2012

How to traerse/print character by character in a string without using strlen() ?

How to traerse/print character by character in a string without using strlen() ?


Usually we will do like this:

char szString[100]={0};
scanf("%s",szString);

for(int i = 0; i <strlen(szString); i++);
{
printf("%c",szString[i];
}


without knowing strlen(), we can print the same thing as below:

char szString[100]={0};
scanf("%s",szString);

for(int i = 0; szString[i]; i++);
{
printf("%c",szString[i];
}

if szString reaches NULL, it will returns zero, so for loop will be
terminated for that case.

Monday, April 16, 2012

find trailing zeros & its importance

How to find trailing zeros in factorial ?

Input : 6 = 2 * 3 * 4 * 5 = 120 = Trailing zeros = 1
Output : 1

For more detailed tutorial :
http://www.purplemath.com/modules/factzero.htm


#include <stdio.h>

void main()
{
long n =0;
long div = 5;
long sum = 0;

printf("Enter N! value:");
scanf("%ld",&n);

while(n >= div)
{
sum += n/div;
div *= 5;
}
printf(" Output is :%ld", sum);
}

Importance of finding the trailing zeros will be useful in floating
point representation.

It will be used to represent floating numbers
as 2 * (10 ^ 3)
mantissa: 2
exponent: 3

Same will be used to represent negative numbers in floating point
representation;

2 * (10 ^ -3)

Wednesday, April 11, 2012

Self synchronization Explicit AV synchronization in Stagefright

Self Synchronization or Explicit AV synchronization:
This is used in any file format. while creating AVI/MPEG4 file,
audio and video encoder data wont be written as such.
Encoded Video and audio frames are written to the file based on interleaving.
AudioFrame: A0 A1 A2
VideoFrame: V0 V1 V2
After interleaving, the data will be as like this: V0 A0 V1 A1 V2 A2
Interleaved data is written into file.
Interleaving can be based on number of frames or duration. Let us say
inteleaved duration is for 1 seconds.
Android stagefright is supporting this interleaved duration. Until
interleave duration is reached, MPEG4Writer will buffers data
in list. Once the interleaved duration is reached, it will be
signalled to MPEG4WriterThread.
MPEG4 Writer thread will write the queued samples in to the file.

Tuesday, April 10, 2012

DirectX Transform Editing Services

http://sworks.com/keng/da/multimedia/dtrans/c++/ - we can have the code for the DirectX Transform samples
http://com.it-berater.org/COM/webbrowser/filters_reference.htm

course on search engine/ text mining

http://net.pku.edu.cn/~course/cs502/2003/

Wednesday, March 14, 2012

AV Sync, Mixing two audio tracks in android

1. AV sync is undetectable if sound is rendered -100ms to +25 ms to video
- Sound Delayed
+ Sound advanced


2.How android audio flinger is mixing two or more tracks in mixer thread ?

 [How to mix two or more audio streams/tracks together ?]

If you want to mix streams A & B, you simply sum the corresponding samples: A1+B1=C1, A2+C2=B2... An+Bn=Cn...
Of course, both streams must have the same sample rate (and with integer formats, both must have the same bit-depth) before you sum.

    With integer formats you have to scale the input streams before summing (i.e. divide by 2), or you need to allow for
larger numbers (more bits) in the output stream. Even with 32-bit floating point, you'll normally want to scale before or after mixing to avoid clipping.
(The 32-bit data won't clip, but you can clip the DAC output.)

And frequently with audio mixing, you'll want to scale the input levels because you don't always want a 1:1 mix... You may want one signal to be louder in the mix.  Audio flinger is mixing one or more tracks as mentioned above.

 

From:http://www.hydrogenaudio.org/forums/index.php?showtopic=79430

 

Sunday, March 11, 2012

How localplayback errors are notified from C++ to java mediaplayer/ mediarecorder layer/Application in android ?

How localplayback errors are notified from C++ to java mediaplayer/ mediarecorder layer/Application in android ?


Java layer will have

MediaPlayer
{
  public static void postEventFromNative() { Notifies Error or Information events to Application thru InfoListener or ErrorListener }

};

JNI:
=====

JNIMediaPlayerListener/ JNIMediaRecorderListener is passed to underlying c++ mediaplayer or mediarecorder [libmedia] object.

whenver C++ mediaplayer or media recorder encounters errors it will call JNIMediaPlayerListener's notify () fn.

JNIMediaPlayerListener's notify/JNIMediaRecorderListener's notify is implemented in JNI.


void JNIMediaPlayerListener/JNIMediaRecorderListener::notify(int msg, int ext1, int ext2, const Parcel *obj)

{
   
    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
  env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
                msg, ext1, ext2, NULL); //This will call the postEventFromNative() fn in Java...
 
}

Tuesday, February 28, 2012

How to detect if one of the linked list pointer is corrupted or not ?

How to detect if one of the linked list pointer is corrupted or not ?

0.In case of doubly linked list, by checking the prev/next pointer, we can identify whether the pointer is valid or not...
1.We can add some extra field to store the count of the linked list node  from 1,2,... and so on. For any node we can check the value with previous node value
2.we can make use of virtualquery() fn in windows to check whether the given address is valid or not.
In the same way, in linux, we will be having mprotect() fn. if we are passing the invalid address in mprotect(), it will notifies the application
with SIGSEGV signal, Application need to catch this signal and do the necessary things.
 

Monday, February 27, 2012

blessing

There is no disaster that cannot become a blessing and no blessing that cannot become a disaster - Richard Bach

Soviet Era math. books link

http://mirtitles.org/

Thursday, January 26, 2012

Lock based synchronization and Lock free synchronization

Lock based synchronization provides the following problems
1.Deadlock

2.LiveLock

3.Priority Inversions

4.Caravan Formation

To avoid these problems, we are going for lock free synchronization. AsynchronousProgramming is a typical technique for achieving lock free synchronization.

Example: Android Stagefright is having lock based synchronization mechanism

PV's OpenCORE is having lock free synchronization mechanism

Tuesday, January 03, 2012

How to add logs into android.mk [to display the information at compile time]

How to add logs into android.mk file:
 
This log will be printed whenever we are compiling.
Usecases: In a large project, somewhere the values will be set, User wont be aware of it.
So that time,to print which device macro is enabled, we can make use of this warning in android.mk

within Android.mk,

ENABLE_CODEC =1
ifeq(ENABLE_CODEC,true)
$(warning SUNDARA::ENABLE_CODEC is true)
else
$(warning SUNDARA::ENABLE_CODEC is false)
endif

#How to print the variable from Android.mk

TARGET_PLATFORM := MSM7227
$(warning SUNDARA::Target Plarform is '$(TARGET_PLATFORM)')

output:
SUNDARA::ENABLE_CODEC is true
Target Plarform is MSM7227