executing ffmpeg command with getRuntime().exec() command - android

i want to run ffmepg command directly on android.
a simple command
ffmpeg -i vid.mp4 out.mp4
now the issue is that i have searched the internet and found the best android ffmpeg can be found here
http://bambuser.com/opensource
I have downloaded it and read the readme file and compiled it. the folder is ffmpeg. I have kept it in <--projectfolder-->/ffmpeg/
there is a ffmpeg executeable file in ffmpeg folder called ffmpeg folder
i have copied it in files folder and run this command
try {
Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show();
Process p = Runtime.getRuntime().exec("/data/data/com.koder.testffmpeg/files/ffmpeg -i /sdcard/vid.mp4 /sdcard/out.mp4");
} catch (IOException e) {
txt.setText(e.toString());
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
according to this link
How do I reduce the video size captured by the default camera using FFMPEG in Android?
but still it does not work always exception i dont know what is going wrong
can someone plz help me with this
java.io.IOException: Error running exec(). Command:[/data/data/com.koder.testffmpeg/files/ffmpeg -i /sdcard/vid.mp4 /sdcard/out.mp4] Working Directory: null Environment:null

You should use getBaseContext().getApplicationInfo().nativeLibraryDir instead of "/data/data/com.example.ffmpegnew/files/"

Give executable permission to ffmpeg like so:
chmod 700 ffmpeg

Try using this:
Process proc = null;
ProcessBuilder pb = new ProcessBuilder();
proc = pb.command("String...yourCommand")
.redirectErrorStream(true).start();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
This code work for me for get system wakelock details in android.may be this will useful to you.

You could combine above answers like this:
Process p = Runtime.getRuntime().exec("chmod 700 "+getBaseContext().getApplicationInfo().nativeLibraryDir + "/ffmpeg ...");

Related

Execute linux command and store output in a file android

I would like to execute 'top -n 1' command using android and store the output of top command in a file in the internal storage in my device, if possible. Otherwise the file should be stored in sd card. I used the following code to achieve it.
File logFile = new File(getFilesDir().getAbsolutePath()+File.separator+"logtex.txt");
if(!logFile.exists())
{
logFile.createNewFile();
}
logFile.setExecutable(true,false);
logFile.setReadable(true,false);
logFile.setWritable(true,false);
Log.e("executeToplog", "err in");
Runtime.getRuntime().exec("top -n 1 > /data/user/0/com.example.abcdef.memcpuusage/files/logtex.txt ");
But it doesn't seem to work. What changes should be made to the code?
I don't like the idea to fill a file with the output. I would try to following
Process process = Runtime.getRuntime ().exec ("top -1 1");
Reader reader = new InputStreamReader (process.getInputStream ());
// simple approach, omit some checkings, not compiled or tested, so may still fail
FileWriter writer = new FileWriter ("top.log");
for (int chr; (chr = reader.read ()) != –1;) {
writer.append((char) chr);
}
writer.close()
However, it may be that android doesn't support "top", may be you need to apply the full path (on my ubuntu /usr/bin/top)
When you need the output into a file, put the content of reader into that file. ">" is a feature of the shell, not of exec

Using FFmpeg without NDK in android

I go though many site and search regarding "FFMPEG" implementation for android project.
Most solution founded are using NDK.
but i want to use FFmpeg without using NDK as i found in This Link
I have used this project
https://github.com/guardianproject/android-ffmpeg-java
It has already compiled for android version of FFMPEG library and this file will be in res/raw folder (you can update this file if you need newer version). You need to add this project as a library to your's. And after thst you can write your own function in java for example like this:
public Clip convert (Clip mediaIn, String outPath, ShellCallback sc) throws Exception
{
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(mFfmpegBin);
cmd.add("-y");
cmd.add("-i");
cmd.add(new File(mediaIn.path).getCanonicalPath());
if (mediaIn.startTime != null)
{
cmd.add("-ss");
cmd.add(mediaIn.startTime);
}
if (mediaIn.duration != -1)
{
cmd.add("-t");
cmd.add(String.format(Locale.US,"%f",mediaIn.duration));
}
Clip mediaOut = new Clip();
File fileOut = new File(outPath);
mediaOut.path = fileOut.getCanonicalPath();
cmd.add(mediaOut.path);
execFFMPEG(cmd, sc);
return mediaOut;
}
and execute it using FfmpegController Object.
Please notice me if you have any questions or if this is what you want.
EDIT:
I hope you connect this github code as a library for your project.
There is FfmpegController.java class in src folder. It's a wrapper for using command line ffmpeg exe file. If you want for example execute command like this one
ffmpeg -i source.wav -b:a 128k output.mp3
you need to add function to FfmpegController.java class. Something like this:
public Clip convert(Clip mediaIn, String outPath, ShellCallback sc) throws Exception
{
ArrayList<String> cmd = new ArrayList<String>();
Clip mediaOut = new Clip();
String mediaPath = mediaIn.path;
cmd = new ArrayList<String>();
cmd.add(mFfmpegBin);
cmd.add("-i");
cmd.add(mediaPath);
cmd.add("-b:a");
cmd.add("128k");
mediaOut.path = outPath;
cmd.add(mediaOut.path);
execFFMPEG(cmd, sc);
return mediaOut; // this is not importatnt because file will be put in outPath
}
Now in your project initialize FfmpegController object and run your function.
I have used this FFmpeg sample which is library that used without NDK
First of download sample example FFmpeg Sample
Download FFmpeg library FFmpeg Library
Extract both in one folder and import project from Android Studio
Now, Calling FFmpeg command
This command is for rotate (/sdcard/videokit/in.mp4) video in 90 Angle and generate out.mp4 in specific location in SD card
ffmpeg -y -i /sdcard/videokit/in.mp4 -strict experimental -vf transpose=1 -s 160x120 -r 30 -aspect 4:3 -ab 48000 -ac 2 -ar 22050 -b 2097k /sdcard/videokit/out.mp4
Now run this command with predefined method in library and add listeners of GeneralUtils
GeneralUtils.copyLicenseFromAssetsToSDIfNeeded(this, workFolder);
GeneralUtils.copyDemoVideoFromAssetsToSDIfNeeded(this, demoVideoFolder);
//demoVideoFolder where your Input file path
//workFolder Absolute path
// workFolder = getApplicationContext().getFilesDir().getAbsolutePath() + "/";
LoadJNI vk = new LoadJNI();
try {
vk.run(GeneralUtils.utilConvertToComplex(commandStr), workFolder, getApplicationContext());
// copying vk.log (internal native log) to the videokit folder
GeneralUtils.copyFileToFolder(vkLogPath, demoVideoFolder);
} catch (Throwable e) {
Log.e(Prefs.TAG, "vk run exeption.", e);
}
Run this and check in File Manager for Output . I hope it works Good :) Enjoy

using overlay video filter in ffmpeg guardian project (android)

First, im a beginner in FFMPEG so please bear with me.
Im using this library and successfully combined an audio and a video :D
However, i keep failing when i tried to insert an image/watermark over a video.
This is the code im using :
public MediaDesc combineVideoAndImage (MediaDesc videoIn, MediaDesc image, MediaDesc out, ShellCallback sc) throws Exception
{
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(ffmpegBin);
cmd.add("-i");
cmd.add(new File(videoIn.path).getCanonicalPath());
cmd.add("-vf");
cmd.add("movie=" + new File(image.path).getAbsolutePath() + " [logo];[in][logo] overlay=10:10 [out]");
cmd.add("-strict");
cmd.add("-2");
File fileOut = new File(out.path);
cmd.add(fileOut.getCanonicalPath());
execFFMPEG(cmd, sc);
return out;
}
Those code will generate this cmd :
ffmpeg -i VIDEONAME.mp4 -vf "movie=LOGONAME.png [logo];[in][logo] overlay=10:10 [out]"
-strict -2 OUTPUTNAME.MP4
I have tested this CMD on ubuntu 13.10 64bit, with latest FFMPEG installed and t succeed.
But it does not in my android project. It does not catch/throw any error/exception, the program running normally and the file is created but has nothing in it (0 byte)
Any help is appreciated. Thanks for your help :D
Try with following command
ffmpeg -i input.mp4 -i watermark.png -filter_complex "overlay=10:10" -codec:a copy output.mp4
i have tested it on android and it is working perfect.

How can I run Linux commands on an Android device?

On some Android devices, in the ADB shell, I can only run echo, cd, ls. When I run:
tar -cvf //mnt/sdcard/BackUp1669/apk/test.tar /mnt/sdcard/test.apk
Or the command cp, it returns:
sh: tar: not found
Why can I not run these commands? Some devices support these commands. My end goal is to copy a file from the /data/data folder to SD card. I got su and I got the following code:
int timeout = 1000;
String command = "tar -cvf /" + Environment.getExternalStorageDirectory() + "/cp/"
+ packageName + ".tar" + " " + path;
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(new DataInputStream(
process.getInputStream())), 64);
String inLine;
try {
StringBuilder sbCommand = new StringBuilder();
sbCommand.append(command).append(" ");
sbCommand.append("\n");
os.writeBytes(command.toString());
if (is != null) {
for (int i = 0; i < timeout; i++) {
if (is.ready())
break;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (is.ready()) {
inLine = is.readLine();
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
}
It always stops in is.ready(), and when I changed it to process.waitfor() it also stopped. Why?
As far as i know, the only way to run shell commands is:
Process proc = Runtime.getRuntime().exec("your command");
You can run Linux commands on Android. But there are usually just very few pre-installed.
If you want to add more commands you might want to root your device and install busybox on it.
This is not for productive use within an application but can help you to work with your device.
If you have the binaries for your system, you can run anything on your system.
Saying that you have to understand that you have to find the binaries for tar.
Look here http://forum.xda-developers.com/showthread.php?t=872438
And possibly other places..
You can probably get this done by using a Terminal Emulator app. As you wrote above, I don't know how well DOS commands will work. But, a Terminal Emulator works without root.
You can install Termux app on your android device and run Linux command by using that app
Install busybox, then type the command in the following format:
busybox [linux command]
You cannot use all the linux commands without busybox, because Android doesn't have all the binaries that are available in a standard linux operating system.
FYI, a binary is just a file that contains compiled code. A lot of the default binaries are stored in /system/bin/sh directory. All these commands like 'cp' 'ls' 'get' etc, are actually binaries. You can view them through:
ls -a /system/bin/sh
Hope this helps.
In reply to Igor Ganapolsky, You would have to have a database set up for locate.
Probably find would be adequate for your needs.
example:
find -name *.apk

How do I get the logfile from an Android device?

I would like to pull the log file from a device to my PC. How can I do that?
Logcollector is a good option but you need to install it first.
When I want to get the logfile to send by mail, I usually do the following:
connect the device to the pc.
Check that I already setup my os for that particular device.
Open a terminal
Run adb shell logcat > log.txt
I hope this code will help someone. It took me 2 days to figure out how to log from device, and then filter it:
public File extractLogToFileAndWeb(){
//set a file
Date datum = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ITALY);
String fullName = df.format(datum)+"appLog.log";
File file = new File (Environment.getExternalStorageDirectory(), fullName);
//clears a file
if(file.exists()){
file.delete();
}
//write log to file
int pid = android.os.Process.myPid();
try {
String command = String.format("logcat -d -v threadtime *:*");
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder result = new StringBuilder();
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
if (currentLine != null && currentLine.contains(String.valueOf(pid))) {
result.append(currentLine);
result.append("\n");
}
}
FileWriter out = new FileWriter(file);
out.write(result.toString());
out.close();
//Runtime.getRuntime().exec("logcat -d -v time -f "+file.getAbsolutePath());
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
//clear the log
try {
Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return file;
}
as pointed by #mehdok
add the permission to the manifest for reading logs
<uses-permission android:name="android.permission.READ_LOGS" />
I would use something of this sort :
$adb logcat -d > logcat.txt
The -d option dumps the entire circular buffer into the text file and if you are looking for a particular action/intent try
$adb logcat -d | grep 'com.whatever.you.are.looking.for' -B 100 -A 100 > shorterlog.txt
Hope this helps :)
For those not interested in USB debugging or using adb there is an easier solution. In Android 6 (Not sure about prior version) there is an option under developer tools: Take Bug Report
Clicking this option will prepare a bug report and prompt you to save it to drive or have it sent in email.
I found this to be the easiest way to get logs. I don't like to turn on USB debugging.
EDIT:
The internal log is a circular buffer in memory. There are actually a few such circular buffers for each of: radio, events, main. The default is main.
To obtain a copy of a buffer, one technique involves executing a command on the device and obtaining the output as a string variable.
SendLog is an open source App which does just this: http://www.l6n.org/android/sendlog.shtml
The key is to run logcat on the device in the embedded OS. It's not as hard as it sounds, just check out the open source app in the link.
Often I get the error "logcat read: Invalid argument". I had to clear the log, before reading from the log.
I do like this:
prompt> cd ~/Desktop
prompt> adb logcat -c
prompt> adb logcat | tee log.txt
I know it's an old question, but I believe still valid even in 2018.
There is an option to Take a bug report hidden in Developer options in every android device.
NOTE: This would dump whole system log
How to enable developer options? see: https://developer.android.com/studio/debug/dev-options
What works for me:
Restart your device (in order to create minimum garbage logs for developer to analyze)
Reproduce your bug
Go to Settings -> Developer options -> Take a bug report
Wait for Android system to collect the logs (watch the progressbar in notification)
Once it completes, tap the notification to share it (you can use gmail or whetever else)
how to read this?
open bugreport-1960-01-01-hh-mm-ss.txt
you probably want to look for something like this:
------ SYSTEM LOG (logcat -v threadtime -v printable -d *:v) ------
--------- beginning of crash
06-13 14:37:36.542 19294 19294 E AndroidRuntime: FATAL EXCEPTION: main
or:
------ SYSTEM LOG (logcat -v threadtime -v printable -d *:v) ------
--------- beginning of main
A simple way is to make your own log collector methods or even just an existing log collector app from the market.
For my apps I made a report functionality which sends the logs to my email (or even to another place - once you get the log you can do whether you want with it).
Here is a simple example about how to get the log file from a device:
http://code.google.com/p/android-log-collector/
Simple just run the following command to get the output to your terminal:
adb shell logcat
Two steps:
Generate the log
Load Gmail to send the log
.
Generate the log
File generateLog() {
File logFolder = new File(Environment.getExternalStorageDirectory(), "MyFolder");
if (!logFolder.exists()) {
logFolder.mkdir();
}
String filename = "myapp_log_" + new Date().getTime() + ".log";
File logFile = new File(logFolder, filename);
try {
String[] cmd = new String[] { "logcat", "-f", logFile.getAbsolutePath(), "-v", "time", "ActivityManager:W", "myapp:D" };
Runtime.getRuntime().exec(cmd);
Toaster.shortDebug("Log generated to: " + filename);
return logFile;
}
catch (IOException ioEx) {
ioEx.printStackTrace();
}
return null;
}
Load Gmail to send the log
File logFile = generateLog();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile));
intent.setType("multipart/");
startActivity(intent);
References for #1
https://stackoverflow.com/a/34883741/2162226
https://stackoverflow.com/a/3359857/2162226
~~
For #2 - there are many different answers out there for how to load the log file to view and send. Finally, the solution here actually worked to both:
load Gmail as an option
attaches the file successfully
Big thanks to https://stackoverflow.com/a/22367055/2162226 for the correctly working answer
Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:
try {
File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}
I have created a small library (.aar) to retrieve the logs by email. You can use it with Gmail accounts. It is pretty simple but works. You can get a copy from here
The site is in Spanish, but there is a PDF with an english version of the product description.
I hope it can help.
First make sure adb command is executable by setting PATH to android sdk platform-tools:
export PATH=/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools:$PATH
then run:
adb shell logcat > log.txt
OR first move to adb platform-tools:
cd /Users/user/Android/Tools/android-sdk-macosx/platform-tools
then run
./adb shell logcat > log.txt
I would use something like:
$ adb logcat --pid=$(adb shell pidof com.example.yourpackage)
which you can then redirect to a file
$ adb logcat --pid=$(adb shell pidof com.example.yourpackage) > log.txt
or if you also want to see it at stdout as well:
$ adb logcat --pid=$(adb shell pidof com.example.yourpackage) | tee log.txt

Categories

Resources