How to stream and download a video using VideoView in Android

Hi there,

It’s been a while I haven’t written anything here, well was busy with my new company and consulting others!

A customer of mine wants to download and play video simultaneously at first I was confidence that  requirement is easy! But it was only a dream because android’s SDK support no such functionality for whatever reason.

But hopefully VideoView supports http streaming and it leads me to implement a HTTP internal server as a fake http streaming server and ask VideoView to get data from it!

it sound quite easy but there are loads of things that you need to take care.

1-creating a HTTP server, thanks Lord there is one for free NanoHTTPD

2-read data in chunks and send it back to VideoView

3-respond to VideoView so it could request for other chunks.

for this part you have to check if VideoView is sending request with “Range” header if not it means it is the first time so you have to response with “Content-Range: bytes 0-YOUR_CHUNK” also you have to send the “Content-Length : full length of file” so that VideoView could request back for other chunks and at the end don’t forget to send your response with “206″ not with “200″.

“HTTP 206″ means partial data!

4-your video files must be encoded correctly otherwise it doesn’t work at all, you can read full article here or just simply download ffmpeg and encode your video with that!

the rest is code : I just copied the useful part here, you can find the full solution in my github

 

    public class VideoStreamServer extends NanoHTTPD
    {
 
        public VideoStreamServer(int port) {
            super(port);
        }
 
        @Override
        public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
 
            //range=bytes=619814-
            long range;
 
            if (headers.containsKey("range"))
            {
                String contentRange = headers.get("range");
                range = Integer.parseInt(contentRange.substring(contentRange.indexOf("=") + 1, contentRange.indexOf("-")));
            }
            else
                range = 0;
 
            byte[] buffer;
            int constantLength = 256000;
            long bufLength=0;
            boolean isLastPart=false;
            try {
 
                RandomAccessFile ff =new RandomAccessFile(new File("/mnt/sdcard","1.mp4"),"rw" );
                long remainingChunk = ff.length() - range; //remaining
                if (remainingChunk < constantLength){
                    bufLength= remainingChunk; //means last part
                    isLastPart = true;
                }
 
                else
                    bufLength = constantLength;
                if (range !=0)
                    ff.seek(range);
                buffer= new byte[(int)bufLength];
 
                ff.read(buffer);
 
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                buffer = new byte[0];
            } catch (IOException e) {
                e.printStackTrace();
                buffer = new byte[0];
            }
            Response response;
 
                response = new Response(Response.Status.PARTIAL_CONTENT,"video/mp4",new ByteArrayInputStream(buffer));
 
            response.addHeader("Content-Length","891064");
            response.addHeader("Content-Range",String.format("bytes %s-%s/%s", range,(range+bufLength),"891064"));
            Log.e("SERVER","Inside server sent " + String.format("bytes %s-%s/%s", range,(range+bufLength),"891064"));
            return response;
 
        }
    }

TDD dilemma or how I learned to stop worrying and practice TDD with support team! (part 1)

Well its been a while I decided to be a good citizen of agile software developing and practice most of the things that agile manifesto suggests. Well obviously they don’t suggest to do TDD but Kent Beck does!

In recent company that I joined I am obligated to implement TDD in the whole software developing team, well at first look it sound quite easy to me but I haven’t foreseen one thing!

Support team, Here comes to boom!

They have a support team and the team is allowed to change code based on customer’s request. that’s the part that I can’t understand it quite well. Why on earth a software company lets his staff to fulfill customer’s request by changing the code on-demand.

At first run I tried to change their mind to have different roles for developers and separate the support team and not to put the supporting on top of developer’s shoulder but since human resource is  kind of an issue in this company so the CEO haven’t agreed on my first suggestion and asked for another solution.

Plan B is to mentoring other folks to use TDD and practice the right way of developing in an enterprise level, to be honest I don’t have any clue what can I do for a support team whose first responsibility is developing(a.k.a fixing) customer’s issue on demand.

The funny thing is I couldn’t find a clue about how to do TDD in support team on the internet. Seems nobody cares or haven’t reached to this point at the time of writing this blog and I’m kinda pioneer at doing such thing on the planet!

Well I thought it is better to start from code structure and try to separate concerns, since there have been an obvious mixed code in view layer and business layer(thanks goodness data access layer is based on an ORM) so at the moment I am busy with refactor their architecture. I guess my next move after this stage would be teaching them unit testing, I will write more about my first hand experience on next post.

So long.

Awesome tool for doing Kanban, the great Trello!

After joining a new company I found out folks and developers at the company are puzzled about Scrum and the way they have to do it. Not so surprisingly they didn’t bothered to have a board for organizing their things! actually the office they have  is stuffed so they had their own excuse to not to use a physical board and since they have been using .Net and MS technologies they are completely dependent(a.k.a falling in love with) on “MS TFS” (an ALM solution which tries to provide a very basic tracking and ticketing system but I couldn’t find a common ground with TFS) and they had preferred the TFS way of ticketing.

TFS is a good solution in terms of being Microsoftish but it is not an awesome piece of software which could solve the problem of tracking issues within the team, specially the GUI of TFS is not user friendly and usable in my opinion.

So I started a revolution to dismiss the TFS and introduced them the awesome piece of software the great Trello!trello

For those of you still haven’t heard  what Trello is. Trello is a web application which helps you to organizing your tasks based on Kanban.

Kanban in Japaneses means “Board” and Trello is nothing but an electronic board which lets you to divide it into numerous columns and name each column and stick your virtual stickers on it.

But Trello still suffers from missed features, the main feature that we missed is an aggregation tool to show all the ‘doing’ cards of an user or show all ‘whatever column’ of an user in one single place so we won’t need to dance around in the website to find out how many tasks are assigned to a user in several boards.

The other feature that we missed is the way Trello folks implement REST api in their application, believe it or not they implement POST methods but they send data through url! whatever reason was their thoughts for doing such, it was a nightmare for us to use a .net wrapper called Chello and find out that the bug we encountered was Trello’s fault.

In Conclusion, Trello still is great, it has potential to become one of the key tool in agile software developing life cycle (well as long as agile is on trend) and become alternative to giants such as TFS! don’t hesitate to use it.

Android AsyncTask and How To Make It Less Painful

If you are an android developer you probably know for doing tasks that take too much time from processor or tasks that keep the user waiting for couple of seconds if you run such task on current thread, android will  freeze the UI therefore you have to develop your application in multi-threading fashion and one of the solutions for making the app multi-threaded is by using AsyncTask abstract class.

Let us check the way of using AsyncTask in a very simplistic example :

(Assume you want to get a page from a url) :

 private class DownloadFilesTask extends AsyncTask {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
 
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
 
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

For executing AsyncTask:

new DownloadFilesTask().execute(url1, url2, url3);

Reference : http://developer.android.com/reference/android/os/AsyncTask.html

But what if you want to use AsyncTask in several different places?
Suppose you want to do several different tasks (e.g. counting a long list or process a text, etc…) If you want to implement AsyncTask everywhere you will end up with a stack of codes which are literally doing the same thing but with very minor changes.

So I thought how can I make it less painful?
I started to write one generic class for AsyncTsak to make it generic and I ended up with something as  following :

But its not the whole story for using this generic class I invent a technique (not quite sure if I can call it “design pattern”) to make it easier to use you need to create following interface as well:

Then inside your actual class you need to implement the ITask and then initialize  the overridden  methods then at the end instantiate the ParrelelTask class to run the actual AsyncTask class behind the scene.

here you can download the sample code to see it in action.

Conclusion

By the help of this technique I manage to reduce lines of codes from several classes inside my real application but yet this technique is not efficient and I think it still can be polished to become less confusing, and remember AsyncTask is not very efficient  in terms of doing several tasks at the same time. The whole idea of AsyncTask is keeping away the UI from freezing for having an actual muti-thread application you need to use JAVA threading APIs.

At the end let me know if you have better way of designing a technique or pattern for calling AsyncTask.

Deep dive into the C macros

Not long ago I was reading an article about C macro and its potential pitfalls and author suggested not to use them more often in the code and he mentioned about some example such as following to expose the problem of macros :

#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int increment(){
static int i=45;
i+=5;
return i;
}
int main(int c,char ** v)
{
int x=20;
printf("the maximum number between %d and %d is : %d",x,increment(),MAX(x,increment()));
return 0;
}

If you try to run this code you will see a very interesting result which makes most of the programmer suspicious about accuracy of C programming language, but the problem is not C. It is resides on macros mechanism and the way compiler treat the macros.

I disassembled the complied version and following is output

.file "macroTest.c"
 .text
 .globl increment
 .type increment, @function
increment:
.LFB0:
 .cfi_startproc
 pushq %rbp
 .cfi_def_cfa_offset 16
 .cfi_offset 6, -16
 movq %rsp, %rbp
 .cfi_def_cfa_register 6
 movl i.2162(%rip), %eax
 addl $5, %eax
 movl %eax, i.2162(%rip)
 movl i.2162(%rip), %eax
 popq %rbp
 .cfi_def_cfa 7, 8
 ret
 .cfi_endproc
.LFE0:
 .size increment, .-increment
 .section .rodata
 .align 8
.LC0:
 .string "the maximum number between %d and %d is : %d"
 .text
 .globl main
 .type main, @function
main:
.LFB1:
 .cfi_startproc
 pushq %rbp
 .cfi_def_cfa_offset 16
 .cfi_offset 6, -16
 movq %rsp, %rbp
 .cfi_def_cfa_register 6
 pushq %rbx
 subq $40, %rsp
 .cfi_offset 3, -24
 movl %edi, -36(%rbp)
 movq %rsi, -48(%rbp)
 movl $20, -20(%rbp)
 movl $0, %eax
 call increment
 cmpl -20(%rbp), %eax
 jl .L4
 movl $0, %eax
 call increment
 movl %eax, %ebx
 jmp .L5
.L4:
 movl -20(%rbp), %ebx
.L5:
 movl $0, %eax
 call increment
 movl %eax, %edx
 movl -20(%rbp), %eax
 movl %ebx, %ecx
 movl %eax, %esi
 movl $.LC0, %edi
 movl $0, %eax
 call printf
 movl $0, %eax
 addq $40, %rsp
 popq %rbx
 popq %rbp
 .cfi_def_cfa 7, 8
 ret
 .cfi_endproc
.LFE1:
 .size main, .-main
 .data
 .align 4
 .type i.2162, @object
 .size i.2162, 4
i.2162:
 .long 45
 .ident "GCC: (Ubuntu/Linaro 4.7.2-4precise1) 4.7.2"
 .section .note.GNU-stack,"",@progbits

As you see there is no clue about macros in compiled code in other words all the macros will be replaced by proper C code during compilation and if you look at assembly code carefully you will see the increament() function called by main() three times rather than two times and the reason is code replacement of compiler.

printf("the maximum number between %d and %d is : %d",x,increment(),MAX(x,increment()));

In above line after calling MAX macro we send the increment() function to MAX macro whereas the defintion of MAX is :

#define MAX(x,y) ((x) > (y) ? (x) : (y))

and the compiler will translate it to something like :

((x) > (increment()) ? (x) : (increment())

as you can see we’re going to get two increment() function in MAX and one in printf() statement and thats the reason of having three calling to increment() inside assembly code.

Conclusion

I am not big fan of making tasks convoluted and I personally think for having a lean and working code its good to step aside from mixed code or combined languages when its unnecessary and this inspection shows how complex it could be in case of using an approach without knowing it thoroughly. So next time think more before making your code complex.

Happy coding!

System.out.print(“Hello World”);

Hi there,

I am Seyed Vahid Hashemi(MscEng) software engineer also an enthusiastic software developer.

I start developing software since I was 14 but as a professional software developer I start when I graduated from high school.

I have been working with different firms form small to big in different areas such as news, media, advertisement, live broadcasting channel, print industry, etc…

I don’t mind about different programming languages or platforms, what I mostly care is best practices in terms of design patterns, approaches, managing projects in software engineering and adapt them in different platforms and technologies.

Here I will share my thoughts and experiences with rest of the world, I will put my thoughts into a bottle  and send it to the vast ocean of internet hope to find the right person at the right time!

You can find me on LinkedIn