how to create video from multiple sequence of images using FFMpeg? - android

Hello all i am new in android developing. I want to create video from sequence of images. And i already fetch images from the specific folder which is resides in external memory card in android devices but i do not know how to use FF MPEG library to convert images into a video file. i had much tried to find out solution but yet i could not get the solution.
Any help would be appreciated and Thanks in advance.
I implement below code but it does not working.
private void convertImg_to_vid() {
// TODO Auto-generated method stub
Process chperm;
try {
chperm=Runtime.getRuntime().exec("su");
DataOutputStream os =
new DataOutputStream(chperm.getOutputStream());
os.writeBytes("ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg\n");
os.flush();
chperm.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You can use -loop command like this ffmpeg -loop 1 -i img.png -c:v libx264 -t 30 -pix_fmt yuv420p out.mp4. This will loop single image as mentioned here.
https://trac.ffmpeg.org/wiki/Create%20a%20video%20slideshow%20from%20images
and the documentation http://ffmpeg.org/ffmpeg.html

Related

Android video encoding with fr and resolution manipulation

I want to be able to take a video recorded with an Android device and encode it to a new Resolution and Frame Rate using my app. The purpose is to upload a much smaller version of the original video (in size), since this will be videos 30 min long or more.
So far, I've read of people saying FFmpeg is they way to go. However, the documentation seems to be lacking.
I have also considered using http opencv http://opencv.org/platforms/android.html
Considering I need to manipulate the video resolution and frame rate, which tool do you think can do such things better? Are there any other technologies to consider?
An important question is, since this will be long videos, is it reasonable to do the encoding in an android device (Consider power resources, time, etc.)
Thanks in advance!
I decided to use ffmpeg to tackle this project. After much researching and trials, I was not able to build ffmpeg for library (using Ubuntu 14.04 LTS.)
However, I used this excellent library https://github.com/guardianproject/android-ffmpeg-java
I just created a project and added that library and it works like a charm. No need to build your own files or mess with the Android NDK. Of course you would still need to build the library yourself if you want to customize it. But it has everything I need.
Here is an example of how I used to lower a video resolution and change the frame rate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// input source
final Clip clip_in = new Clip("/storage/emulated/0/Developer/test.mp4");
Activity activity = (Activity) MainActivity.this;
File fileTmp = activity.getCacheDir();
File fileAppRoot = new File(activity.getApplicationInfo().dataDir);
final Clip clip_out = new Clip("/storage/emulated/0/Developer/result2.mp4");
//put flags in clip
clip_out.videoFps = "30";
clip_out.width = 480;
clip_out.height = 320;
clip_out.videoCodec = "libx264";
clip_out.audioCodec = "copy";
try {
FfmpegController fc = new FfmpegController(fileTmp, fileAppRoot);
fc.processVideo(clip_in, clip_out, false, new ShellUtils.ShellCallback() {
#Override
public void shellOut(String shellLine) {
System.out.println("MIX> " + shellLine);
}
#Override
public void processComplete(int exitValue) {
if (exitValue != 0) {
System.err.println("concat non-zero exit: " + exitValue);
Log.d("ffmpeg","Compilation error. FFmpeg failed");
Toast.makeText(MainActivity.this, "result: ffmpeg failed", Toast.LENGTH_LONG).show();
} else {
if(new File( "/storage/emulated/0/Developer/result2.mp4").exists()) {
Log.d("ffmpeg","Success file:"+ "/storage/emulated/0/Developer/result2.mp4");
}
}
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// automated try and catch
setContentView(R.layout.activity_main);
}
}
The function processVideo produces a command similar to ffmpeg -i input -s 480X320 -r 30 -vcodec libx264 -acodec copy output
This a very simple example, but it outputted the same kind of conversion done by ffmpeg desktop. This codes needs lots of work! I hope it helps anyone.

How to stream video in android device via .sdp file from android device

I had anapplication to stream video(without audio) from android device(Blaze board) to PC. For that, I'm using vlc player to view streamed video by using the following command in command line
vlc stream.sdp
This .sdp file would be generated from my application. By using the above command, I can stream from blaze board to PC with the delay of 1 sec.
Now, My problem is that, I have to stream from one blaze board to another blaze board. I have searched a lot. But, Nothing is worked.
I have an idea to write viewer application ( For client ). This application will use sdp file path as url. I refer this page. Here, he had used "setDataSource(http://localhost/file.sdp)" . I used like this in my application. But, it also, didn't work.
String videoSrc = "rtsp://192.168.13.77:8086/stream.sdp";
Here is my code
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoSrc);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How to use .sdp file to play streamed video lively?
Whether I am going is correct path or not? If you are having any other way, please suggest me.
Any help will be appreciated.

Running ffmpeg commands from android ffmpeg syntax error in logcat

I have successfully compiled ffmpeg for android and have ported it.
I placed
libffmpeg.so in /system/lib directory
ffmpeg executable in /system/bin and /system/xbin directory (i was not sure where to place it). i directly copied ffmpeg executable from source directory (Not sure whether it's a correct way)
Now i am executing commands from android with following code !!
imports *
public class LatestActivity extends Activity {
private Process process;
String command,text;
static {
System.loadLibrary("ffmpeg");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest);
//Execute Command !!
try {
Execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Execute() throws IOException, InterruptedException{
try {
File dir=new File("/system/bin");
String[] cmd= {"ffmpeg","-codecs"};
process=Runtime.getRuntime().exec(cmd,null,dir);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Process IOException starts:",e.getMessage());
e.printStackTrace();
Log.d("System Manual exit !!",e.getMessage());
System.exit(MODE_PRIVATE);
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()),16384);
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// read the output from the command
Log.d("Application output: ","Output if any !");
while ((text = stdInput.readLine()) != null) {
Log.d("Output: ",text); //$NON-NLS-1$
}
text="";
// read any errors from the attempted command
Log.d("Application output: ","Errors if any !"); //$NON-NLS-1$
while ((text = stdError.readLine()) != null) {
Log.d("Error: ",text); //$NON-NLS-1$
}
stdInput.close();
stdError.close();
process.waitFor();
process.getOutputStream().close();
process.getInputStream().close();
process.getErrorStream().close();
destroyProcess(process);
//process.destroy();
}
private static void destroyProcess(Process process) {
try {
if (process != null) {
// use exitValue() to determine if process is still running.
process.exitValue();
}
} catch (IllegalThreadStateException e) {
// process is still running, kill it.
process.destroy();
}
}
}
And Here is the logcat output:
09-05 15:29:13.287: D/dalvikvm(2670): No JNI_OnLoad found in /system/lib/libffmpeg.so 0x44e7e910, skipping init
09-05 15:29:29.117: I/global(2670): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
09-05 15:29:29.117: D/Application output:(2670): Output if any !
09-05 15:29:29.117: D/Application output:(2670): Errors if any !
09-05 15:29:29.127: D/Error:(2670): /system/bin/ffmpeg: 1: Syntax error: "(" unexpected
m neither getting any errors nor output of command. At the end it shows syntax error. I want to know what kind of syntax error it is. how to tackle it?
m i doing something wrong?
This Error occurs if the ffmpeg file does not compiled for your cpu architechture.
Your commands might be right but you need to find correct ffmpeg file.
FIXED
#Gaganpreet Singh
You are right after so much research on this, I have got to know that CPU Chip-set matters too, FFMPEG commands doesn't support INTEL ATOM processor.
Asus Memo Pad 7 using INTEL ATOM cpu chip-set and when trying running ffmpeg command on it, it crashes and throw error "SYNTAX ERROR"
My commands working perfectly on all the devices except the device using INTEL ATOM chipset.
Please review this and this link if it will be helpful for you.
If anyone finds a solution. Please share with us.
Finally Fixed this issue by creating ffmpeg lib for x64 & armv7 using NDK. And used this Library in my Andriod project. Now I have 2 lib and using this lib for different Android CPU ARCH.
Please check this link too. Very helpful.

How to delete a system file from an Android App?

I'm using Root Tools and I'm not getting too far with it...
I want to have access to delete files from /system/app and other directories that require root. I would love to do it programmatically through Java, but if I can do it through shell commands, that's OK. Too. My phone is rooted. Here's what I've tried so far.
RootTools.remount("/system", "rw");
try {
RootTools.sendShell("rm /system/app/Videos.apk", -1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RootToolsException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I've also tried:
public static void sendShell(List<String> cmds) throws Exception {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
os.close();
process.waitFor();
}
I have no idea what to do from here...
Based on our conversations it looks like you need a different rom as there were issues remounting partitions on your device.
I would bet that flashing a new rom would alleviate this issue and allow RootTools to properly remount /system as rw and allow you to delete your file.

How to execute shell commands in android?

I am trying to execute shell command through my code for adding entry in Iptables. The following is my piece of code
private void createShellCommand(String uidValue_param, String interface_param) {
// TODO Auto-generated method stub
StringBuilder cmdScript=new StringBuilder();
script.append("iptables -A OUTPUT " + interface_param + "-m owner --uid-owner " + uidValue_param + "-j REJECT");
writeIptables(cmdScript);
}
private void writeIptables(StringBuilder scriptfile) {
// TODO Auto-generated method stub
String cmd=scriptfile.toString();
if(RootTools.isRootAvailable())
{
Process exec;
try {
exec = Runtime.getRuntime().exec(new String[]{"su","-c"});
final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream());
out.write(cmd);
// Terminating the "su" session
out.write("exit\n");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IPtables updation failed", "Iptable write failed"+e);
}
}
else
{
Log.e("Root Access denied", "Access Denied");
}
}
Here there are two methods i.e, createshellCommand() for building the shell command and writeIptables() for updating the iptables. But whenever I run the program logcat is displaying the following warning
"W 19913 su request rejected (0->0 /system/bin/sh)"
But I can manually add the entry through command prompt and its adding to the iptables but by using the above code its not updating. My phone is rooted and I am using android 2.3.4 with linux kernel 2.6.29. And I am using external library "Roottools" for checking the root access.
Please help me to rectify the error.
This Works:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
execute_reboot();
}
void execute_reboot()
{
Process reboot;
try {
reboot=Runtime.getRuntime().exec("su");
DataOutputStream os =
new DataOutputStream(reboot.getOutputStream());
os.writeBytes("reboot\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
reboot.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This Code Works fine. There are couple of small mistakes in your program. Try the one i pasted. Its working charm. All the best. I kept it as simple as possible so that it is easy to understand. You can still use arrays and other stuff to fancy your coding.
And yaa the same one also works for chmod command where you need to pass more than one argument.
For this Just replace
"os.writeBytes("reboot\n");"
with
"chmod 777 /dev/video0\n"(or any other system file).
Thanks. LEt me know if there is something tat i can do.
public static void rebootNow() {
Log.d(TAG, "Rebooting");
try {
#SuppressWarnings("unused")
Process proc = Runtime.getRuntime().exec(
new String[] { "su", "-c", "reboot" });
} catch (Exception ex) {
Log.d(TAG, "Rebooting failed (Terminal Error)");
}
}
This one is a little more compact
You can add "proc.waitFor();" after the Process proc... line to get rid of the unused warning, but rebooting your device takes a few seconds time and if you want to disable some features during the few seconds in your UI-thread, I think its better to not wait for the process to end.
Trying using the iptables command (with sudo and without), rather than just clobbering the iptables config file.

Categories

Resources