Skip to content

Instantly share code, notes, and snippets.

@sasasa671
Created May 16, 2015 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sasasa671/4868d59a9d5b82e3fa69 to your computer and use it in GitHub Desktop.
Save sasasa671/4868d59a9d5b82e3fa69 to your computer and use it in GitHub Desktop.
package com.sethaikens.videotimestamp;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.provider.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import java.io.*;
import android.database.*;
import android.widget.AdapterView.*;
import java.nio.channels.*;
import android.content.res.*;
import android.util.*;
import java.lang.Process;
import java.util.*;
import java.util.regex.*;
import android.app.Notification;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import com.sethaikens.videotimestamp.R;
public class MainActivity extends Activity
{
public Button btnRecord;
public Button btnAirplaneMode;
public TextView txtVideoInfo;
static final int REQUEST_VIDEO_CAPTURE = 1;
public String sdcard_path;
public String VIDEO_FOLDER_NAME = "Body Cam";
public String video_folder_path;
public String data_folder_path;
public String video_info_dump;
public String video_created_at;
public int video_width;
public int video_height;
public float video_fps;
public int VIDEO_FONT_SIZE = 30;
public String VIDEO_FONT_COLOR = "#FFFFFF";
public String VIDEO_TIME_FORMAT="00:00:00:00";
public void create_alert(String title, String message){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher).setContentTitle(title).setContentText(message);
int mNotificationId = 1;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
startManagingCursor(cursor);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copyFile(String sourceImagePath, String destinationImagePath){
try {
File sd = Environment.getExternalStorageDirectory();
//File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File source= new File(sourceImagePath);
File destination= new File(destinationImagePath);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {}
}
public void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData();
final String videoFullPath = getPath(videoUri);
//long current_time = System.currentTimeMillis()/1000L;
//String new_video_path = video_folder_path+"/video_"+current_time+".mp4";
//copyFile(videoFullPath, new_video_path);
//txtVideoInfo.setText("video "+videoFullPath+" copied to sdcard");
//txtVideoInfo.setText(get_video_info(videoFullPath));
txtVideoInfo.setText("Please Wait... Encoding Video");
video_info_dump = get_video_info(videoFullPath);
extract_video_info(video_info_dump);
EncodeTimestamp task = new EncodeTimestamp();
task.execute(new String[] {videoFullPath});
//add_timestamp(videoFullPath);
//txtVideoInfo.setText(videoFullPath);
}
}
/*public void add_timestamp(String video_path){
String command=data_folder_path+"/ffmpeg";
long current_time = System.currentTimeMillis()/1000L;
String new_video_path = video_folder_path+"/video_"+current_time+".mp4";
int video_center=10;
String text="";
text += "drawtext=";
text += "fontfile="+data_folder_path+"/Arial.ttf"+": ";
text += "text=\\'"+video_created_at+"\\ \\ \\ \\ \\': ";
text += "timecode=\\'"+VIDEO_TIME_FORMAT+"\\': ";
text += "rate="+video_fps+": ";
text += "x="+video_center+": ";
text += "y=10: ";
text += "fontsize="+VIDEO_FONT_SIZE+": ";
text += "fontcolor="+VIDEO_FONT_COLOR;
txtVideoInfo.setText("");
// ffmpeg -i $1 -strict -2 -vf "drawtext=fontfile=Arial.ttf: text='$CREATION_TIME\ \ \ \ ': timecode='$TIME_FORMAT': rate=$FRAME_RATE: x=$VIDEO_CENTER: y=10: fontsize=$FONT_SIZE: fontcolor=$FONT_COLOR" -preset ultrafast -f mp4 $2
try {
Process process = new ProcessBuilder(command, "-i", video_path, "-strict", "-2", "-vf", text, "-preset", "ultrafast", "-f", "mp4", new_video_path).start();
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
txtVideoInfo.setText(txtVideoInfo.getText()+line+"\n");
}
create_alert("Video encoder", "video is done encoding "+new_video_path);
}
catch (IOException e){
txtVideoInfo.setText(e.getMessage());
}
}*/
public String get_video_info(String video_path){
String result="";
String command=data_folder_path+"/ffmpeg";
try {
Process process = new ProcessBuilder(command, "-i", video_path).start();
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
//System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
result+=line+"\n";
//System.out.println(line);
}
return result;
}
catch (IOException e){
txtVideoInfo.setText(e.getMessage());
}
return result;
}
public void extract_video_info(String video_info_dump){
Matcher m;
StringBuilder temp;
/* video size */
m = Pattern.compile("[0-9]{2,}+x[0-9]+").matcher(video_info_dump);
if(m.find()) {
video_width = Integer.parseInt(m.group(0).split("x")[0]);
video_height = Integer.parseInt(m.group(0).split("x")[1]);
}
/* video creation date time */
m = Pattern.compile("(?<=creation_time).*").matcher(video_info_dump);
if(m.find()) {
temp = new StringBuilder(m.group(0));
temp.deleteCharAt(temp.indexOf(":"));
video_created_at = temp.toString().trim();
}
/* frames per second */
m = Pattern.compile("[0-9]+(.)?[0-9]+ fps").matcher(video_info_dump);
if(m.find()) {
video_fps = Float.parseFloat(m.group(0).split(" ")[0]);
}
}
public void init_assets(){
data_folder_path = "/data/data/"+this.getPackageName()+"/files";
File data_folder = new File(data_folder_path);
if(!data_folder.exists()){
copyFileOrDir("files");
}
video_folder_path = sdcard_path+"/"+VIDEO_FOLDER_NAME;
File exe = new File(data_folder+"/ffmpeg");
exe.setExecutable(true);
File folder = new File(data_folder_path);
File[] listOfFiles = folder.listFiles();
String temp=null;
for (int i = 0; i < listOfFiles.length; i++) {
temp += listOfFiles[i].getName()+"\n";
/*if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}*/
}
//txtVideoInfo.setText(temp);
File video_folder = new File(video_folder_path);
if(!video_folder.exists()){
video_folder.mkdir();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnRecord = (Button) findViewById(R.id.btnRecord);
btnAirplaneMode = (Button) findViewById(R.id.settings_link_button);
txtVideoInfo = (TextView) findViewById(R.id.txtVideoInfo);
txtVideoInfo.setTextIsSelectable(true);
File sd = Environment.getExternalStorageDirectory();
sdcard_path = sd.getAbsolutePath();
init_assets();
txtVideoInfo.setText(getResources().getString(R.string.app_instructions));
btnRecord.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
dispatchTakeVideoIntent();
}
});
btnAirplaneMode.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
startActivity(new Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS));
}
});
}
private class EncodeTimestamp extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String[] p1) {
String video_path = p1[0];
String command=data_folder_path+"/ffmpeg";
long current_time = System.currentTimeMillis()/1000L;
String new_video_path = video_folder_path+"/video_"+current_time+".mp4";
int video_center=10;
String response="";
String text="";
text += "drawtext=";
text += "fontfile="+data_folder_path+"/Arial.ttf"+": ";
text += "text=\\'"+video_created_at+"\\ \\ \\ \\ \\': ";
text += "timecode=\\'"+VIDEO_TIME_FORMAT+"\\': ";
text += "rate="+video_fps+": ";
text += "x="+video_center+": ";
text += "y=10: ";
text += "fontsize="+VIDEO_FONT_SIZE+": ";
text += "fontcolor="+VIDEO_FONT_COLOR;
// ffmpeg -i $1 -strict -2 -vf "drawtext=fontfile=Arial.ttf: text='$CREATION_TIME\ \ \ \ ': timecode='$TIME_FORMAT': rate=$FRAME_RATE: x=$VIDEO_CENTER: y=10: fontsize=$FONT_SIZE: fontcolor=$FONT_COLOR" -preset ultrafast -f mp4 $2
try {
Process process = new ProcessBuilder(command, "-i", video_path, "-strict", "-2", "-vf", text, "-preset", "ultrafast", "-f", "mp4", new_video_path).start();
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
response += line+"\n";
}
}
catch (Exception e){
response = e.getMessage();
}
return response;
}
@Override
protected void onPostExecute(String result) {
txtVideoInfo.setText(result);
create_alert("Video Encoder", "video is done encoding");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment