Sunday, April 14, 2013

Why StagefrightPlayer and AwesomePlayers are available? why the application cant directly calling the AwesomePlayer instead of StagefrightPlayer and internally how Stagefrightplayer is calling AwesomePlayer ???

In OpenCore also, as similar to AwesomePlayer we will have PlayerDriver.
All things will be routed via PlayerDriver from PvPlayer class.

  AwesomePlayer is a proxy to stagefrightPlayer . It is using pimpl design pattern.This is to reduce the header file resources needed.
If we have to use AwesomePlayer directly we need to include more header files related with Awesomeplayer. This is covered in stagefright player.So the user can use stagefrightplayer.h header file without
adding multiple headers files in libmediaplayer/mediaplayer.cpp

 To know more about PIMPL design pattern:
http://www.codeproject.com/Articles/17536/Use-of-PIMPL-Design-Pattern

Labels: , ,

Adding custom return type for marshalling/unmarshalling the data type in AIDL:

In Android application, while working with AIDL, I faced this problem.

If I am going to return any custom datatype or class in interface's functions, then we need to write .aidl and .java file.

For example from my AIDL interface function, I am going to return Rect custom class. Then I have to do the following:


Rect.aidl:
=========
package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;


Rect.java
==============


import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }

        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };

    public Rect() {
    }

    private Rect(Parcel in) {
        readFromParcel(in);
    }

    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

I have to include this Rect.java in android compilation make file [make];

we should not include the .aidl file in Android.mk for this scenario.

This can happen when we are using NDK compilation. In NDK case, we will include java/include files in Android.mk.

Error:

* in my Android.mk file, I have added:
LOCAL_SRC_FILES += \
        src/com/mycompany/mypackage/Rect.aidl \

But when we compile we will
Aidl: Test <= src/com/mycompany/mypackage//Rect.aidl
src/com/mycompany/mypackage/Rect.aidl:19 aidl can only generate
code for interfaces, not parcelables,
src/com/mycompany/mypackage/Rect.aidl:19 .aidl files that only
declare parcelables don't need to go in the Makefile.

Labels: , ,

Android Application AIDL error:

In android application, while working with AIDL, I observed an error.
My function is returning the class Employee. But I got the below error

Aidl: huey <= external/testapp/IMyService.aidl
external/testapp/Ioffice.aidl:16: couldn't find import for class com.sundar.Employee
make: *** [out/target/common/obj/JAVA_LIBRARIES/MyService_intermediates/src/com/IMyService.java] Error 1


IMyService.aidl

interface IOffice
{
 Employee get();
};


I have added the Employee.java which is derived from Parcelable class. I have also added this java file in make file.
But still I got this error.

How to resolve it:
I created the Employee.aidl and copied the below contents

package com.MyService;
parcelable Employee;

I copied the Employee.aidl and copied to the folder where Employee.java is there.Afterwards, it is compiling fine without any error.
 But Employee.aidl is not at all added in Android.mk

Labels: , , ,

What is cyclomatic complexity ?

Testing is the process by which all the code should be executed once to identify the bugs/errors in a product/system.
In testing there is a concept called cylomatic complexity through which we can identify all the executable path/flow.

Will it be useful only for testing ?

  while testing, we can try with all inputs which satify all the executable paths in a code.
we have to test with all the inputs which will cover all the executable paths. This will ensure that
code in a product/system executed only once.

Will it be useful for development?

It will be useful for enhancing the existing product/integrate new components to the existing product. On such a development case,
we can idenfity the executable paths and inputs. After the enhancement/adding new component, we can test with previously identified executable paths and inputs also we have
to add new executable paths and inputs for the  addition of new components/enhancements.


Labels: ,

Saturday, April 13, 2013

How to get result from an activity:
=====================================

The following program snippet depicts how we can get result from an activity in an android application.

To launch an activity:
===========================
    Intent pickIntent= new Intent(this,PickServerActivity.class);
    //To launch an activity use below command:
    startActivityForResult(pickIntent, REQUEST_CODE_PICK_SERVER);

within activity, how to set result:
====================================
  Intent intent = new Intent();
  // start intent
   if(bServerSelected)
   {   
      intent.putExtra(ServerIntents.EXTRA_SERVER_NAME, selectedServerName);
      setResult(RESULT_OK, intent);
    } else {
          setResult(RESULT_CANCELED, intent);
     }

To get result from an activity:
====================================

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_SERVER) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    mServerName = extras.getString(EXTRA_SERVER_NAME);
            //Display Selected server from the activity   
                }
           
            }
        }
    }
   

Labels: , , ,

How to use bundle in Android Application:
===============================
    /** bundle got from intent. */
    private Bundle mExtras = null;

    if (mExtras == null) {
           mExtras = new Bundle();
     }
     mExtras.putString(MESSGAGE,
                    "Hello World");

Other end:
     message = mExtras.getString( MESSAGE);

Labels: ,

Tuesday, March 19, 2013

How DVD chapters were implemented?

   DVD movies contains chapters. The user can browse chapters to view the DVD contents.Once the user has selected the movie chapter, the corresponding movie chapter is played on TV or system.

We might have seen the DVD movie with chapters as follows:
  1) chapter 1,2,3 or play video songs, list of songs in DVD

How it is possible?
   Every chapter has some information like chapter thumbnail [which will be shown while showing the chapter list],
chapter's starting position [milli seconds] in DVD video file.

  When the user has selected the movie chapter, the player application will seek to the chapter's starting position in a video.

  Example:
     chapter 1,120 ms
     chapter 2,360 ms #chapter 2 is starting from 360 ms of the DVD video file whenever the user select this chapter
                      #player application will seek to 360 ms and play the video



Some players have support for moving to next chapter. Usually the player code will have the below logic:

     if ( chapterAvailableForVideo)
     {
         //if chapters are available, next/previous buttons are mapped to switch to next/prev chapter
          map(nextbutton,NextChapter);
          map(prevButton,PrevChapter);
     }
     else
     {
         map(nextButton,forward);
         map(prevButton,rewind);
     }   
   

    onSelectNext()
    {
        if(chapterAvailableForVideo)
         {
              switchTo(nextChapter);  //get next chapter's starting position, seekto this position
                                      // and play video on screen
      }
         else
         {
            doForward();
         }

    }
    onSelectPrev()
    {
        if(chapterAvailableForVideo)
         {
              switchTo(prevChapter);
      }
         else
         {
            doRewind();
         }
     }

Labels: ,

Maximum Subarray Sum Source code:

 //maximum crossing subarray
int mcs(int array[],int low, int mid,int high)
{
    result res={0};
    int i =0;
    int left_sum =  -100000;//INT_MIN;
    int right_sum =  -100000;//INT_MIN;
    int sum = 0;
    for(i=mid; i >= 0;i--)
    {
       sum += array[i] ;
       if( sum > left_sum)
       {
            left_sum = sum;
       }

    }

    sum = 0;

    for(i=mid+1; i < high;i++)
    {
       sum += array[i] ;
       if( sum > right_sum)
       {
            right_sum = sum;
       }

    }
   return  left_sum + right_sum;

}

int maximum(int a, int b, int c)
{
    if( (a >= b) && (a >=c))
    {
        return a;
    }
    else if( (b >= a) && (b >=c))
    {
        return b;
    }
    return c;
}

int maxsum(int array[], int low,int high)
{
     int max1,max2,max3;
     if( low == high)
     {
         return array[low];
     }
     int mid = (low +high)/2;
     max1= maxsum(array,low,mid);
     max2= maxsum(array,mid+1, high);
     max3= mcs(array,low,mid,high);

     return maximum(max1,max2,max3);

}

void test()
{
    int array[] = {31,-41,59,26,-53,58,97,-93,-23,84};
    int arraySize = sizeof(array) / sizeof(array[0]) ;
    printf("\n maximum subarray sum=%d",maxsum(array,0,arraySize-1));

}
void main()
{
   test();
}

Labels:

Tuesday, March 12, 2013

Different ways to find the magnitude pole of an array:

1) logic: bruteforce
    start from beginning of an array to end of an array and check all the before elements are <= the item and right elements are
> than it.

    O(n^2) Time complexity
    O(1) space complexity

2) logic: If any item is a magnitude pole of an array, then its position wont change after sorting 

   2.1) copy the original array into another array
   2.2) sort  it using o(n^2) insertion/bubble sort or o(n logn) merge sort.
   2.3) Check the original and sorted array  if any item is equal, return the index.
    if no match is found, return -1
  
   O (n log n) time complexity
   O (n) space complexity

   This approach may fail with below inputs:

            2 5 3 1 4
    ascending:  1 2 3 4 5

            2 1 3 5 4   
 

3) logic:If any item is a magnitude pole of an array, then  it will be the maximum and minimum of an array index.

   O(n) time complexity
   O(n) space complexity
  
 3.1) start from beginning and find max of array index[Extra array]
 3.2) start from end and find min of array index [change inplace of original array]
 3.3) Check the max and min array  if any item is equal, return the index.
    if no match is found, return -1
    
   
4) with simple code: o(n) time
                     o(1) space
  int magnitudePole(int a[])
   {
    int i_pole = 0;
    int i_max  = 0;
    bool have_pole = true;
    for (int i = 1; i < N; i++)
    {
        if (A[i] < A[i_pole])
        {
            have_pole = false;
        }
        if (A[i] > A[i_max])
        {
            i_max = i;
            if (!have_pole)
            {
                i_pole = i;
            }
            have_pole = true;
            cout <<endl<< " It has pole @" << i_pole;   
        }
    }
    if( have_pole)
    {
      // cout <<endl<< " It has pole @" << i_pole;   
       return i_pole;
    }
   
    return -1;
   }

5) o(n) time complexity
THis is also similar to max and min approach instead of comparing
min and max arrays, they are using BitSet class to do this job.


 import java.util.BitSet;
public static int magnitudePole(int[] A) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
BitSet bits1 = new BitSet(A.length);
BitSet bits2 = new BitSet(A.length);
for (int i = 0; i < A.length; ++i) {
if (A[i] >= max) {
bits1.set(i);
max = A[i];
}
}
for (int i = A.length - 1; i >= 0; --i) {
if (A[i] <= min) {
bits2.set(i);
min = A[i];
}
}
System.out.println(bits1.toString());
System.out.println(bits2.toString());
bits1.and(bits2);
return bits1.nextSetBit(0);
}

Labels:

Tuesday, February 26, 2013

Apply BinarySearch in Debugging:


1)Problem1:
   I faced the problem in mips processor environment.
My program is crashing without giving any error or crash log.
I couldnt find the exact location of the crash.

Prior Expectation:
    We should know about the complete flow of the program.


How to find the crash location:

Apply binary search to enable logs.Add logs in middle of the code, if we are getting logs, we have a problem after middle part of the code.If we didnt get the log,the problem lies from beginning to middle of the program.


2) problem 2:
   For analysing performance of the program,
we have to find/optimize part of the program which is taking more time.

 How we can find this part of the program:

    Apply binary search to identify which part/statements taking more time.


  



 

Labels: ,

Tuesday, February 19, 2013

Some  creational design patterns not mentioned in designpatterns book:

   1)Multiton - As similar to singleton, different objects with single instance . I am having one car and one bike.this is multiton.
    if I am having only instance of bike,singleton comes to picture.
   2)Object pool - to improve performance and avoid runtime creation/deletion of objects by allocating pool of objects
                 - This will avoid memory fragments
       Example:
            1)balls in Snow bowling
                [3 or 6 balls are gathered at a time before   playing it]
            2)RingBuffer- Allocates predefined buffer or frame sizes and reuse
               it without deleting and creating it at runtime

  3)Resource Acquisition Is Initialization [RAAI]            - whenever we forget to release the memory pointer or mutex locks,this can be used
                - Writing a class around the pointers to allocate memory/acquire mutex lock on constructor and release the memory pointer or release the mutex lock in destructor.
            -if we are using this class, it will be stored in object. whenever client fn is using it,it will be stored in stack. whenver function goes out of stack, it will automatically deallocate or release the resources. client fn doesnt need to take care of releasing resources on every failure and success return cases.

   4) Lazy initialization           - Delaying of memory allocation at runtime whenever the user is requesting,that time only resources will be allocated in memory

Labels:


Server component: it is an actual implementation of code which is providing services to client
Client component:
    Client component uses the services of the server component

if we implemented the calculator functionaity as server component.Client component is the one which is using this calculator functionality.

Design pattern with real usecase scenarios:

What is the purpose of Object Oriented Design?

   Objective of the Object Oriented Design is to create the loosely coupled client and server components, so that it
can allow us to add features with minimal changes, allows us to extend the features.Every design has its own merits and demerits.Mostly merits and demerits are unknown to the designer based on his exposure or intelligence.

       Design patterns are proven design with known merits and demerits. Objective of the design pattern is to create loosely coupled design components.

Design pattern has 3 different categories:
   1) Creational design pattern
   2) Structural design pattern
   3) Behavioral design pattern

1)Situations to use creational design pattern     I) when we need to simplify the object creation logic
     II) Decoupling client logic regardless of frequent changes in Object creation logic
2) Situations to use Structural design pattern:
     I) building new types or exending existing types
     II) new types addition with simple design
     III) Overcome problems like class explosion and machine resource limitations

3)Situation to use behavioral design pattern:     I)object communication with loosely coupled design
     II)scalable design with respect to addition/modification of algorithms
     III) division of responsibility to classes


Creational design patterns:
 1) Abstract Factory pattern:
        creates family of related classes. without changing client logic, we can provide different services from server.
     It is mainly used in frameworks.Multimedia framework uses Plugins for decoder/encoder/parsers. Example:
     Directshow MMF filters,GStreamer,OpenCORE plugins,Media Foundation transform plugins

 2)Builder pattern     - Separates object construction from its representation
     Sample application from Wiki is confusing...
 3) Factory method -creates instance of several derived classes
      - Similar to abstract factory pattern
 4) Prototype:       copying or cloning an instance
       Ex:If the client is accessing elements via Iterator pattern, if it wants to clone an object, it can do it by this prototype pattern.
 whenever client is having access to interface if it wants to copy or clone an object, it can make use of the clone.
   
    class IEncoder
        {
           public :
                virtual IEncoder* clone() = 0;
        };
       class CJpegEncoder: public IEncoder
       {
          public:
                CJpegEncoder(){}
                ~CJpegEncoder(){}
        virtual IEncoder* clone() { return new CJpegEncoder();}
       };
        Client code:
    IEncoder *pEncoder = new CJpegEncoder();
        IEncoder* pEncoder2 == pEncoder->clone(); //creating the copy of an instance or cloning of an instance

  5)Singleton-class of which only a single instance can exist
    Example: Single window manager instance to manage multiple windows in GUI
     note:use private constructor and private copy constructor without definition to disable others to create/copy the object
 
         
Structural design patterns:

 6)Adapter or wrapper or translator -match interfaces of different classes.
        Ex: From UI to database updation, we can directly add UI data to database. Instead of it, add intermediate class. so UI validation will be done in upper layer,only database required fields are passed as a structure or class object to database.

  while reading from database also, read as an object or structure and interpret it according to UI. We will be able to add UI or database changes with minimal changes.

 7)Bridge Pattern- decouples an abstraction from implementation.Graphical User Interface Frameworks use the bridge pattern to separate abstractions from platform specific implementation.For example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.

 8)Composite pattern- A tree structure of simple and composite objects
         Ex: Filesystem - file system contains files,folders in a tree structure
             Graphics Editor can have the one shape or more shapes inside another shape or group of shapes
  
 9)Decorator- add responsibilities to objects dynamically
     Ex:Implement the window draw and develop the derived class HorizontalScrollbar window by overriding draw with drawing horizontal bar to window.

10) Facade - single class represents the entire subsystem.A facade is an object that provides a simplified interface to a larger body of code, such as a class library.Ex:Computer is a single class that represents the CPU,memory,OS entire subsystem.

11)Flyweight pattern- This is mainly used to reduce memory footprint
   Ex:whenever we want to display the Verdana font 'a', it will have more bytes to represent the pixels in verdana font 'a'.  Instead of using all the pixels, just assign some ASCII character and map it to the predefined verdana font 'a' pixels.
   
12)Proxy - an object representing another object
       this is used to minimize the dependencies. if the class is accessing more header files, instead of accesing this class from client, provide the proxy class with minimal dependancies, so the client can use it without any problem
  Ex: StageFrightPlayer and AwesomePlayer. All AwesomePlayer calls are being invoked from StagefrightPlayer.   

 This StagefrightPlayer proxy class is used in mediaplayerservice.cpp which contains many player creations.

  Ex 2: proxy class between remoting server and client

Behavioral design patterns:
  13)Chain of Responsibility: 
-a way of passing request between chain of objects
        - base class will have a sequence of pointers to the derived classes. Default window have the capability to handle UI operations.
         From this window, Button,OptionButton,checkbox windows are created in Windows SDK. If Button clicks are not handled, the default
        window will handle the scenarios. Ex: Quit or closing the window If the user/application doesnt provide implementation, the default window handles it.
     Ex: Item purchase order,the purchase request is sent to multiple managers/admins. when any one has approved it,
         proceed to process the purchase request further.
     Ex2:whenever mouse clicks or UI clicks are not handled by application, the default window handles it . if the application overrides/handles it, then the default/framework window wont handle the clicks in Windows or GUI OS.  

  14)Command - Encapsulates a command request as an object
      Ex1:Enqueueing the commands to the queue and processing it in event loop
      Ex2:Implementation example: passing AMessage request object to ALooper class in android
      Ex3:Adding cut,copy,paste command operations, parameters as an object to queue and processing it with appropriate cut,copy and paste operation in word or graphics editor

 15) Interpreter - this is used to interpret the language.Difficult to understand...
 16) Iterator -sequentially access the server elements as collection.It will gives the total number of elements and get functions to access the individual elements Examples: Iterators in C++ STL, Iterators in C#/java
 17) Mediator -defines an object that encapsulates how a set of objects interact.Ex: Dialog which can hold combo box control or label control or textbox control. The value changes are updated/controlled by dialog.The controls are not aware of the existence of other controls .   

18) Memento
- provides ability to restore object's previous state.
   Ex:Undo operation in Word/Graphics Editor, rollback operation in Database

19) Observer - Ex: register the callback function to the server components and server will notify the client by calling this function on any error or failure or any important events.
   this is also called as publish-subscriber pattern.

20) State pattern:
       - provides cleaner way to provide an object to change its behavior at runtime.  This state based pattern is used in Jellybean's ACodec implementation which will be used in NuPlayer on HLS scenario.

21)strategy pattern     - wrapper class around a runtime polymorphism.This wrapper class will be used by clients.
22) template pattern- Ex: C++ template class
23) Visitor pattern
- little bit confusing..
        
    
              
 

Labels:

Friday, January 18, 2013


Android Compilation  & use emulator:
=======================
source build/envsetup.sh
lunch sdk-eng
make sdk

This will build the android code.


We can use emulator to test the compiled code.

mksdcard -l sdjb 256M sdjb.img
emulator -sdcard sdjb.img


This code launches the emulator.Emulator makes use of system.img. System.img is nothing but the compressed format of output system folder
binaries.

If we are pushing any data to sdcard

Push data to sdcard:
adb push test.3gp /sdcard

copy data from sdcard to current folder:
adb pull /sdcard/test.3gp .

We can also use DDMS to copy file to/from device.
Afterwards, we can check gallery. It will list the sdcard in gallery and will show the copied test.3gp in gallery.By clicking it we can play the video. we can also see the logs using adb logcat command.

To compile module level code & use it in emulator follow below steps:
we can use

cd frameworks/av/media/libstagefright
touch AwesomePlayer.cpp
mm

This will generate the module level compilation.

After module level compilation to reflect in emulator's system.img
  give

 "make snod"
from android filesystem.


or

do the following:
cd frameworks/av/media/libstagefright
touch AwesomePlayer.cpp
mmm

mmm will compile the current directory code,dependency code and will update the system.img with modified binaries.

Labels: , ,