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