Thursday, 22 September 2011

UPnP with Java


UPnP: Universal Plug and Play


Universal Plug and Play (UPnP) is a set of networking protocols for primarily residential networks without enterprise class devices that permits networked devices, such as personal computers, printers, Internet gateways, Wi-Fi access points and mobile devices to seamlessly discover each other's presence on the network and establish functional network services for data sharing, communications, and entertainment. The UPnP technology is promoted by the UPnP Forum.
The concept of UPnP is an extension of plug-and-play, a technology for dynamically attaching devices directly to a computer, although UPnP is not directly related to the earlier plug-and-play technology. UPnP devices are "plug-and-play" in that when connected to a network they automatically establish working configurations with other devices.

Cling - Java/Android UPnP library and tools

Cling is an effort to create a UPnP-compatible software stack in Java. The project's goals are strict specification compliance, complete, clean and extensive APIs, as well as rich SPIs for easy customization.
The current release of Cling is 1.0.5 (2011-09-22), see the Changelog for a summary of improvements and the Road Mapfor future plans. You can also find snapshot builds of the current development trunk here or include version 1.1-SNAPSHOTas a dependency in your Maven pom.xml.
Read this chapter of the manual for a simple Cling usage example.
Main modules of Cling are:
Cling is Free Software, distributed under the terms of the GNU Lesser General Public License.

Wednesday, 21 September 2011

Android: Services

Declaring a service in the manifest

Add a <service> element as a child of the <application> element.

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

android:name attribute is the only required attribute, that specifies the class name of the service. Once you publish your application, you should not change this name.
Just like an activity, a service can define intent filters that allow other components to invoke the service using implicit intents. If you plan on using your service only locally, then you you don't need to supply any intent filters.
Additionally, you can ensure that your service is private to your application only if you include the android:exported attribute and set it to "false".

Creating a Started Service


When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService().
An application component such as an activity can start the service by callingstartService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.


Traditionally, there are two classes you can extend to create a started service:
Service
This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
The IntentService does the following:
  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent()implementation.
Example of IntentService implementation...
public class HelloIntentService extends IntentService {

  /** 
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}


Starting a Service

Intent intent = new Intent(this, HelloService.class);
startService(intent);


Running a Service in the Foreground

A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification for the status bar. For example:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
To remove the service from the foreground, call stopForeground(). This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.

Lifecycle of Services



http://developer.android.com/guide/topics/fundamentals/services.html

Monday, 12 September 2011

How to detect if internet connection is available on Android


private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Thursday, 8 September 2011

Logging for Android Debugging

Methods of logging
- ERROR: Log.e()
- WARN: Log.w()
- Info: Log.i()
- DEBUG: Log.d()
- VERBOSE: Log.v()

How to:
1. Add a TAG as a class member like this.
    private static final String TAG = "MyClass";
2. Where you want to log, put line like this.
    Log.e(TAG, "value=" + i);

Tuesday, 6 September 2011

FFserver configuration for FLV streaming

This is for FLV streaming from FFserver.


Port            8090
BindAddress     0.0.0.0
MaxClients      1000
MaxBandWidth    50000
CustomLog       -
NoDaemon


<Feed office.ffm>
File            /tmp/office.ffm
FileMaxSize     20M
</Feed>


<Stream office.flv>
Feed etioffice.ffm
Format flv
VideoCodec flv
VideoFrameRate 10
#VideoBitRate 2048
#VideoBufferSize 4096
VideoSize 640x480
VideoQMin 3
VideoQMax 31
AVOptionVideo flags +global_header 
#VideoGopSize 10
VideoIntraOnly
PreRoll 0
NoAudio
</Stream>

FFserver configuration for MJPEG streaming


This is the configuration for MJPEG streaming. My test case is getting MJPEG streaming from IP Camera and transcode to another MJPEG video stream. This was needed as my IP cam limits the available connection to 10. It works well but sometimes it reports error like "invalid stream index xxx", which needs to be investigated.

The configuration is like this.

Port            8090
BindAddress     0.0.0.0
MaxClients      1000
MaxBandWidth    50000
CustomLog       -
NoDaemon


<Feed office.ffm>
File            /tmp/office.ffm
FileMaxSize     20M
</Feed>


<Stream office.mjpeg>
Feed office.ffm
Format mpjpeg
VideoFrameRate 10
#VideoBitRate 2048
#VideoBufferSize 4096
VideoSize 640x480
VideoQMin 3
VideoQMax 31
NoAudio
Strict -1
</Stream>

Monday, 5 September 2011

Rotate bitmap to display on ImageView

SetImage function doesn't detect photo orientation. This code is to fix the problem.
At first, detect the orientation then apply this code to draw properly.

int iImageWidth = 320; // original image width
int iImageHeight = 240; // original image height

Bitmap bmOrg = null; 
BufferedInputStream bis;
try {
    bis = new BufferedInputStream(new FileInputStream(mPathImage));
    bmOrg = BitmapFactory.decodeStream(bis); 
    try {
        bis.close();
    } catch (IOException e) {
    e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(iToRotate);
Bitmap resizedBitmap = Bitmap.createBitmap(bmOrg, 0, 0, iImageWidth, iImageHeight, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
mImageView.setImageDrawable(bmd);
mImageView.setScaleType(ScaleType.CENTER_INSIDE);

Public DNS

Google Public DNS is a free, global Domain Name System (DNS) resolution service, that you can use as an alternative to your current DNS provider.


Configure your network settings to use the IP addresses 8.8.8.8 and 8.8.4.4 as your DNS servers.
Sometimes DNS server of Internet service provider is down and causes internet service unavailable even though connection is valid. Setting this addresses could be one of the solutions.

How to rotate video with FFmpeg

Use  video fileter graph option with -vf "transpose=X".

Transpose rows with columns in the input video and optionally flip it.
It accepts a parameter representing an integer, which can assume the values:

0: Rotate by 90 degrees counterclockwise and vertically flip (default)
1: Rotate by 90 degrees clockwise
2: Rotate by 90 degrees counterclockwise
3. Rotate by 90 degrees clockwise and vertically flip

Example:



ffmpeg -vf "transpose=1" -i input.mp4 output.mp4