TrimVideo.java revision 2833355c86cff90163457779adb2bc78a6ca0faa
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.gallery3d.app;
18
19import android.app.ActionBar;
20import android.app.Activity;
21import android.app.ProgressDialog;
22import android.content.ContentResolver;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.Intent;
26import android.database.Cursor;
27import android.media.MediaPlayer;
28import android.net.Uri;
29import android.os.Bundle;
30import android.os.Environment;
31import android.os.Handler;
32import android.provider.MediaStore;
33import android.provider.MediaStore.Video;
34import android.provider.MediaStore.Video.VideoColumns;
35import android.view.View;
36import android.view.ViewGroup;
37import android.view.Window;
38import android.widget.TextView;
39import android.widget.Toast;
40import android.widget.VideoView;
41
42import com.android.gallery3d.R;
43import com.android.gallery3d.util.BucketNames;
44
45import java.io.File;
46import java.io.IOException;
47import java.sql.Date;
48import java.text.SimpleDateFormat;
49
50public class TrimVideo extends Activity implements
51        MediaPlayer.OnErrorListener,
52        MediaPlayer.OnCompletionListener,
53        ControllerOverlay.Listener {
54
55    private VideoView mVideoView;
56    private TrimControllerOverlay mController;
57    private Context mContext;
58    private Uri mUri;
59    private final Handler mHandler = new Handler();
60    public static final String TRIM_ACTION = "com.android.camera.action.TRIM";
61
62    public ProgressDialog mProgress;
63
64    private int mTrimStartTime = 0;
65    private int mTrimEndTime = 0;
66    private int mVideoPosition = 0;
67    public static final String KEY_TRIM_START = "trim_start";
68    public static final String KEY_TRIM_END = "trim_end";
69    public static final String KEY_VIDEO_POSITION = "video_pos";
70    private boolean mHasPaused = false;
71
72    private String mSrcVideoPath = null;
73    private String mSaveFileName = null;
74    private static final String TIME_STAMP_NAME = "'TRIM'_yyyyMMdd_HHmmss";
75    private File mSrcFile = null;
76    private File mDstFile = null;
77    private File mSaveDirectory = null;
78    // For showing the result.
79    private String saveFolderName = null;
80
81    @Override
82    public void onCreate(Bundle savedInstanceState) {
83        mContext = getApplicationContext();
84        super.onCreate(savedInstanceState);
85
86        requestWindowFeature(Window.FEATURE_ACTION_BAR);
87        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
88
89        ActionBar actionBar = getActionBar();
90        int displayOptions = ActionBar.DISPLAY_SHOW_HOME;
91        actionBar.setDisplayOptions(0, displayOptions);
92        displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM;
93        actionBar.setDisplayOptions(displayOptions, displayOptions);
94        actionBar.setCustomView(R.layout.trim_menu);
95
96        TextView mSaveVideoTextView = (TextView) findViewById(R.id.start_trim);
97        mSaveVideoTextView.setOnClickListener(new View.OnClickListener() {
98            @Override
99            public void onClick(View arg0) {
100                trimVideo();
101            }
102        });
103
104        Intent intent = getIntent();
105        mUri = intent.getData();
106        mSrcVideoPath = intent.getStringExtra(PhotoPage.KEY_MEDIA_ITEM_PATH);
107        setContentView(R.layout.trim_view);
108        View rootView = findViewById(R.id.trim_view_root);
109
110        mVideoView = (VideoView) rootView.findViewById(R.id.surface_view);
111
112        mController = new TrimControllerOverlay(mContext);
113        ((ViewGroup) rootView).addView(mController.getView());
114        mController.setListener(this);
115        mController.setCanReplay(true);
116
117        mVideoView.setOnErrorListener(this);
118        mVideoView.setOnCompletionListener(this);
119        mVideoView.setVideoURI(mUri);
120
121        playVideo();
122    }
123
124    @Override
125    public void onResume() {
126        super.onResume();
127        if (mHasPaused) {
128            mVideoView.seekTo(mVideoPosition);
129            mVideoView.resume();
130            mHasPaused = false;
131        }
132        mHandler.post(mProgressChecker);
133    }
134
135    @Override
136    public void onPause() {
137        mHasPaused = true;
138        mHandler.removeCallbacksAndMessages(null);
139        mVideoPosition = mVideoView.getCurrentPosition();
140        mVideoView.suspend();
141        super.onPause();
142    }
143
144    @Override
145    public void onStop() {
146        if (mProgress != null) {
147            mProgress.dismiss();
148            mProgress = null;
149        }
150        super.onStop();
151    }
152
153    @Override
154    public void onDestroy() {
155        mVideoView.stopPlayback();
156        super.onDestroy();
157    }
158
159    private final Runnable mProgressChecker = new Runnable() {
160        @Override
161        public void run() {
162            int pos = setProgress();
163            mHandler.postDelayed(mProgressChecker, 200 - (pos % 200));
164        }
165    };
166
167    @Override
168    public void onSaveInstanceState(Bundle savedInstanceState) {
169        savedInstanceState.putInt(KEY_TRIM_START, mTrimStartTime);
170        savedInstanceState.putInt(KEY_TRIM_END, mTrimEndTime);
171        savedInstanceState.putInt(KEY_VIDEO_POSITION, mVideoPosition);
172        super.onSaveInstanceState(savedInstanceState);
173    }
174
175    @Override
176    public void onRestoreInstanceState(Bundle savedInstanceState) {
177        super.onRestoreInstanceState(savedInstanceState);
178        mTrimStartTime = savedInstanceState.getInt(KEY_TRIM_START, 0);
179        mTrimEndTime = savedInstanceState.getInt(KEY_TRIM_END, 0);
180        mVideoPosition = savedInstanceState.getInt(KEY_VIDEO_POSITION, 0);
181    }
182
183    // This updates the time bar display (if necessary). It is called by
184    // mProgressChecker and also from places where the time bar needs
185    // to be updated immediately.
186    private int setProgress() {
187        mVideoPosition = mVideoView.getCurrentPosition();
188        // If the video position is smaller than the starting point of trimming,
189        // correct it.
190        if (mVideoPosition < mTrimStartTime) {
191            mVideoView.seekTo(mTrimStartTime);
192            mVideoPosition = mTrimStartTime;
193        }
194        // If the position is bigger than the end point of trimming, show the
195        // replay button and pause.
196        if (mVideoPosition >= mTrimEndTime && mTrimEndTime > 0) {
197            if (mVideoPosition > mTrimEndTime) {
198                mVideoView.seekTo(mTrimEndTime);
199                mVideoPosition = mTrimEndTime;
200            }
201            mController.showEnded();
202            mVideoView.pause();
203        }
204
205        int duration = mVideoView.getDuration();
206        if (duration > 0 && mTrimEndTime == 0) {
207            mTrimEndTime = duration;
208        }
209        mController.setTimes(mVideoPosition, duration, mTrimStartTime, mTrimEndTime);
210        return mVideoPosition;
211    }
212
213    private void playVideo() {
214        mVideoView.start();
215        mController.showPlaying();
216        setProgress();
217    }
218
219    private void pauseVideo() {
220        mVideoView.pause();
221        mController.showPaused();
222    }
223
224    // Copy from SaveCopyTask.java in terms of how to handle the destination
225    // path and filename : querySource() and getSaveDirectory().
226    private interface ContentResolverQueryCallback {
227        void onCursorResult(Cursor cursor);
228    }
229
230    private void querySource(String[] projection, ContentResolverQueryCallback callback) {
231        ContentResolver contentResolver = getContentResolver();
232        Cursor cursor = null;
233        try {
234            cursor = contentResolver.query(mUri, projection, null, null, null);
235            if ((cursor != null) && cursor.moveToNext()) {
236                callback.onCursorResult(cursor);
237            }
238        } catch (Exception e) {
239            // Ignore error for lacking the data column from the source.
240        } finally {
241            if (cursor != null) {
242                cursor.close();
243            }
244        }
245    }
246
247    private File getSaveDirectory() {
248        final File[] dir = new File[1];
249        querySource(new String[] {
250                VideoColumns.DATA }, new ContentResolverQueryCallback() {
251
252            @Override
253            public void onCursorResult(Cursor cursor) {
254                dir[0] = new File(cursor.getString(0)).getParentFile();
255            }
256        });
257        return dir[0];
258    }
259
260    private void trimVideo() {
261        int delta = mTrimEndTime - mTrimStartTime;
262        // Considering that we only trim at sync frame, we don't want to trim
263        // when the time interval is too short or too close to the origin.
264        if (delta < 100 ) {
265            Toast.makeText(getApplicationContext(),
266                getString(R.string.trim_too_short),
267                Toast.LENGTH_SHORT).show();
268            return;
269        }
270        if (Math.abs(mVideoView.getDuration() - delta) < 100) {
271            Toast.makeText(getApplicationContext(),
272                getString(R.string.trim_too_long),
273                Toast.LENGTH_SHORT).show();
274            return;
275        }
276        // Use the default save directory if the source directory cannot be
277        // saved.
278        mSaveDirectory = getSaveDirectory();
279        if ((mSaveDirectory == null) || !mSaveDirectory.canWrite()) {
280            mSaveDirectory = new File(Environment.getExternalStorageDirectory(),
281                    BucketNames.DOWNLOAD);
282            saveFolderName = getString(R.string.folder_download);
283        } else {
284            saveFolderName = mSaveDirectory.getName();
285        }
286        mSaveFileName = new SimpleDateFormat(TIME_STAMP_NAME).format(
287                new Date(System.currentTimeMillis()));
288
289        mDstFile = new File(mSaveDirectory, mSaveFileName + ".mp4");
290        mSrcFile = new File(mSrcVideoPath);
291
292        showProgressDialog();
293
294        new Thread(new Runnable() {
295            @Override
296            public void run() {
297                try {
298                    TrimVideoUtils.startTrim(mSrcFile, mDstFile, mTrimStartTime, mTrimEndTime);
299                    // Update the database for adding a new video file.
300                    insertContent(mDstFile);
301                } catch (IOException e) {
302                    e.printStackTrace();
303                }
304                // After trimming is done, trigger the UI changed.
305                mHandler.post(new Runnable() {
306                    @Override
307                    public void run() {
308                        Toast.makeText(getApplicationContext(),
309                            getString(R.string.save_into) + " " + saveFolderName,
310                            Toast.LENGTH_SHORT)
311                            .show();
312                        // TODO: change trimming into a service to avoid
313                        // this progressDialog and add notification properly.
314                        if (mProgress != null) {
315                            mProgress.dismiss();
316                            mProgress = null;
317                            // Show the result only when the activity not stopped.
318                            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
319                            intent.setDataAndTypeAndNormalize(Uri.fromFile(mDstFile), "video/*");
320                            intent.putExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION, false);
321                            startActivity(intent);
322                            finish();
323                        }
324                    }
325                });
326            }
327        }).start();
328    }
329
330    private void showProgressDialog() {
331        // create a background thread to trim the video.
332        // and show the progress.
333        mProgress = new ProgressDialog(this);
334        mProgress.setTitle(getString(R.string.trimming));
335        mProgress.setMessage(getString(R.string.please_wait));
336        // TODO: make this cancelable.
337        mProgress.setCancelable(false);
338        mProgress.setCanceledOnTouchOutside(false);
339        mProgress.show();
340    }
341
342    /**
343     * Insert the content (saved file) with proper video properties.
344     */
345    private Uri insertContent(File file) {
346        long now = System.currentTimeMillis() / 1000;
347
348        final ContentValues values = new ContentValues(12);
349        values.put(Video.Media.TITLE, mSaveFileName);
350        values.put(Video.Media.DISPLAY_NAME, file.getName());
351        values.put(Video.Media.MIME_TYPE, "video/mp4");
352        values.put(Video.Media.DATE_TAKEN, now);
353        values.put(Video.Media.DATE_MODIFIED, now);
354        values.put(Video.Media.DATE_ADDED, now);
355        values.put(Video.Media.DATA, file.getAbsolutePath());
356        values.put(Video.Media.SIZE, file.length());
357        // Copy the data taken and location info from src.
358        String[] projection = new String[] {
359                VideoColumns.DATE_TAKEN,
360                VideoColumns.LATITUDE,
361                VideoColumns.LONGITUDE,
362                VideoColumns.RESOLUTION,
363        };
364
365        // Copy some info from the source file.
366        querySource(projection, new ContentResolverQueryCallback() {
367            @Override
368            public void onCursorResult(Cursor cursor) {
369                values.put(Video.Media.DATE_TAKEN, cursor.getLong(0));
370                double latitude = cursor.getDouble(1);
371                double longitude = cursor.getDouble(2);
372                // TODO: Change || to && after the default location issue is
373                // fixed.
374                if ((latitude != 0f) || (longitude != 0f)) {
375                    values.put(Video.Media.LATITUDE, latitude);
376                    values.put(Video.Media.LONGITUDE, longitude);
377                }
378                values.put(Video.Media.RESOLUTION, cursor.getString(3));
379
380            }
381        });
382
383        return getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI, values);
384    }
385
386    @Override
387    public void onPlayPause() {
388        if (mVideoView.isPlaying()) {
389            pauseVideo();
390        } else {
391            playVideo();
392        }
393    }
394
395    @Override
396    public void onSeekStart() {
397        pauseVideo();
398    }
399
400    @Override
401    public void onSeekMove(int time) {
402        mVideoView.seekTo(time);
403    }
404
405    @Override
406    public void onSeekEnd(int time, int start, int end) {
407        mVideoView.seekTo(time);
408        mTrimStartTime = start;
409        mTrimEndTime = end;
410        setProgress();
411    }
412
413    @Override
414    public void onShown() {
415    }
416
417    @Override
418    public void onHidden() {
419    }
420
421    @Override
422    public void onReplay() {
423        mVideoView.seekTo(mTrimStartTime);
424        playVideo();
425    }
426
427    @Override
428    public void onCompletion(MediaPlayer mp) {
429        mController.showEnded();
430    }
431
432    @Override
433    public boolean onError(MediaPlayer mp, int what, int extra) {
434        return false;
435    }
436}
437