CaptureSessionImpl.java revision b62fa4716df6bcc526f575006822e06dd8ea9b83
1/*
2 * Copyright (C) 2015 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.camera.session;
18
19import android.graphics.Bitmap;
20import android.graphics.BitmapFactory;
21import android.location.Location;
22import android.net.Uri;
23import android.os.AsyncTask;
24
25import com.android.camera.app.MediaSaver;
26import com.android.camera.data.FilmstripItemData;
27import com.android.camera.debug.Log;
28import com.android.camera.exif.ExifInterface;
29import com.android.camera.util.FileUtil;
30import com.android.camera.util.Size;
31
32import java.io.File;
33import java.io.IOException;
34import java.util.HashSet;
35
36/**
37 * The default implementation of the CaptureSession interface. This is the
38 * implementation we use for normal Camera use.
39 */
40public class CaptureSessionImpl implements CaptureSession {
41    private static final Log.Tag TAG = new Log.Tag("CaptureSessionImpl");
42
43    /** The capture session manager responsible for this session. */
44    private final CaptureSessionManagerImpl mSessionManager;
45    /** Used for adding/removing/updating placeholders for in-progress sessions. */
46    private final PlaceholderManager mPlaceholderManager;
47    /** Used to store images on disk and to add them to the media store. */
48    private final MediaSaver mMediaSaver;
49    /** The title of the item being processed. */
50    private final String mTitle;
51    /** These listeners get informed about progress updates. */
52    private final HashSet<ProgressListener> mProgressListeners = new HashSet<>();
53    private final long mSessionStartMillis;
54    /**
55     * The file that can be used to write the final JPEG output temporarily,
56     * before it is copied to the final location.
57     */
58    private final TemporarySessionFile mTempOutputFile;
59    /** Saver that is used to store a stack of images. */
60    private final StackSaver mStackSaver;
61    /** A URI of the item being processed. */
62    private Uri mUri;
63    /** The location this session was created at. Used for media store. */
64    private Location mLocation;
65    /** The current progress of this session in percent. */
66    private int mProgressPercent = 0;
67    /** A message ID for the current progress state. */
68    private CharSequence mProgressMessage;
69    /** A place holder for this capture session. */
70    private PlaceholderManager.Session mPlaceHolderSession;
71    private Uri mContentUri;
72    /** Whether this image was finished. */
73    private volatile boolean mIsFinished;
74
75    /**
76     * Creates a new {@link CaptureSession}.
77     *
78     * @param title the title of this session.
79     * @param sessionStartMillis the timestamp of this capture session (since
80     *            epoch).
81     * @param location the location of this session, used for media store.
82     * @param temporarySessionFile used to create a temporary session file if
83     *            necessary.
84     * @param captureSessionManager the capture session manager responsible for
85     *            this session.
86     * @param placeholderManager used to add/update/remove session placeholders.
87     * @param mediaSaver used to store images on disk and add them to the media
88     *            store.
89     * @param stackSaver used to save stacks of images that belong to this
90     *            session.
91     */
92    /* package */CaptureSessionImpl(String title,
93            long sessionStartMillis, Location location, TemporarySessionFile temporarySessionFile,
94            CaptureSessionManagerImpl captureSessionManager, PlaceholderManager placeholderManager,
95            MediaSaver mediaSaver, StackSaver stackSaver) {
96        mTitle = title;
97        mSessionStartMillis = sessionStartMillis;
98        mLocation = location;
99        mTempOutputFile = temporarySessionFile;
100        mSessionManager = captureSessionManager;
101        mPlaceholderManager = placeholderManager;
102        mMediaSaver = mediaSaver;
103        mStackSaver = stackSaver;
104        mIsFinished = false;
105    }
106
107    @Override
108    public String getTitle() {
109        return mTitle;
110    }
111
112    @Override
113    public Location getLocation() {
114        return mLocation;
115    }
116
117    @Override
118    public void setLocation(Location location) {
119        mLocation = location;
120    }
121
122    @Override
123    public synchronized int getProgress() {
124        return mProgressPercent;
125    }
126
127    @Override
128    public synchronized void setProgress(int percent) {
129        mProgressPercent = percent;
130        mSessionManager.notifyTaskProgress(mUri, mProgressPercent);
131        for (ProgressListener listener : mProgressListeners) {
132            listener.onProgressChanged(percent);
133        }
134    }
135
136    @Override
137    public synchronized CharSequence getProgressMessage() {
138        return mProgressMessage;
139    }
140
141    @Override
142    public synchronized void setProgressMessage(CharSequence message) {
143        mProgressMessage = message;
144        mSessionManager.notifyTaskProgressText(mUri, message);
145        for (ProgressListener listener : mProgressListeners) {
146            listener.onStatusMessageChanged(message);
147        }
148    }
149
150    @Override
151    public void updateThumbnail(Bitmap bitmap) {
152        mPlaceholderManager.replacePlaceholder(mPlaceHolderSession, bitmap);
153        mSessionManager.notifyTaskQueued(mUri);
154        onPreviewAvailable();
155    }
156
157    @Override
158    public synchronized void startEmpty(Size pictureSize) {
159        if (mIsFinished) {
160            return;
161        }
162
163        mProgressMessage = "";
164        mPlaceHolderSession = mPlaceholderManager.insertEmptyPlaceholder(mTitle, pictureSize,
165                mSessionStartMillis);
166        mUri = mPlaceHolderSession.outputUri;
167        mSessionManager.putSession(mUri, this);
168        mSessionManager.notifyTaskQueued(mUri);
169        onPreviewAvailable();
170    }
171
172    @Override
173    public synchronized void startSession(Bitmap placeholder, CharSequence progressMessage) {
174        if (mIsFinished) {
175            return;
176        }
177
178        mProgressMessage = progressMessage;
179        mPlaceHolderSession = mPlaceholderManager.insertPlaceholder(mTitle, placeholder,
180                mSessionStartMillis);
181        mUri = mPlaceHolderSession.outputUri;
182        mSessionManager.putSession(mUri, this);
183        mSessionManager.notifyTaskQueued(mUri);
184        onPreviewAvailable();
185    }
186
187    @Override
188    public synchronized void startSession(byte[] placeholder, CharSequence progressMessage) {
189        if (mIsFinished) {
190            return;
191        }
192
193        mProgressMessage = progressMessage;
194
195        mPlaceHolderSession = mPlaceholderManager.insertPlaceholder(mTitle, placeholder,
196                mSessionStartMillis);
197        mUri = mPlaceHolderSession.outputUri;
198        mSessionManager.putSession(mUri, this);
199        mSessionManager.notifyTaskQueued(mUri);
200        onPreviewAvailable();
201    }
202
203    @Override
204    public synchronized void startSession(Uri uri, CharSequence progressMessage) {
205        mUri = uri;
206        mProgressMessage = progressMessage;
207        mPlaceHolderSession = mPlaceholderManager.convertToPlaceholder(uri);
208
209        mSessionManager.putSession(mUri, this);
210        mSessionManager.notifyTaskQueued(mUri);
211    }
212
213    @Override
214    public synchronized void cancel() {
215        if (isStarted()) {
216            mSessionManager.removeSession(mUri.toString());
217        }
218    }
219
220    @Override
221    public synchronized void saveAndFinish(byte[] data, int width, int height, int orientation,
222            ExifInterface exif, final MediaSaver.OnMediaSavedListener listener) {
223        mIsFinished = true;
224        if (mPlaceHolderSession == null) {
225            mMediaSaver.addImage(
226                    data, mTitle, mSessionStartMillis, mLocation, width, height,
227                    orientation, exif, listener);
228            return;
229        }
230        mContentUri = mPlaceholderManager.finishPlaceholder(mPlaceHolderSession, mLocation,
231                orientation, exif, data, width, height, FilmstripItemData.MIME_TYPE_JPEG);
232
233        mSessionManager.removeSession(mUri.toString());
234        mSessionManager.notifyTaskDone(mPlaceHolderSession.outputUri);
235    }
236
237    @Override
238    public StackSaver getStackSaver() {
239        return mStackSaver;
240    }
241
242    @Override
243    public void finish() {
244        if (mPlaceHolderSession == null) {
245            throw new IllegalStateException(
246                    "Cannot call finish without calling startSession first.");
247        }
248
249        mIsFinished = true;
250        AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
251            @Override
252            public void run() {
253                byte[] jpegDataTemp;
254                if (mTempOutputFile.isUsable()) {
255                    try {
256                        jpegDataTemp = FileUtil.readFileToByteArray(mTempOutputFile.getFile());
257                    } catch (IOException e) {
258                        return;
259                    }
260                } else {
261                    return;
262                }
263                final byte[] jpegData = jpegDataTemp;
264
265                BitmapFactory.Options options = new BitmapFactory.Options();
266                options.inJustDecodeBounds = true;
267                BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options);
268                int width = options.outWidth;
269                int height = options.outHeight;
270                int rotation = 0;
271                ExifInterface exif = null;
272                try {
273                    exif = new ExifInterface();
274                    exif.readExif(jpegData);
275                } catch (IOException e) {
276                    Log.w(TAG, "Could not read exif", e);
277                    exif = null;
278                }
279                CaptureSessionImpl.this.saveAndFinish(jpegData, width, height, rotation, exif,
280                        null);
281            }
282        });
283
284    }
285
286    @Override
287    public TemporarySessionFile getTempOutputFile() {
288        return mTempOutputFile;
289    }
290
291    @Override
292    public Uri getUri() {
293        return mUri;
294    }
295
296    @Override
297    public void updatePreview() {
298        final File path;
299        if (mTempOutputFile.isUsable()) {
300            path = mTempOutputFile.getFile();
301        } else {
302            Log.e(TAG, "Cannot update preview");
303            return;
304        }
305        AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
306            @Override
307            public void run() {
308                byte[] jpegDataTemp;
309                try {
310                    jpegDataTemp = FileUtil.readFileToByteArray(path);
311                } catch (IOException e) {
312                    return;
313                }
314                final byte[] jpegData = jpegDataTemp;
315
316                BitmapFactory.Options options = new BitmapFactory.Options();
317                Bitmap placeholder = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
318                        options);
319                mPlaceholderManager.replacePlaceholder(mPlaceHolderSession, placeholder);
320                onPreviewAvailable();
321            }
322        });
323    }
324
325    @Override
326    public void finishWithFailure(CharSequence reason) {
327        if (mPlaceHolderSession == null) {
328            throw new IllegalStateException(
329                    "Cannot call finish without calling startSession first.");
330        }
331        mProgressMessage = reason;
332        mSessionManager.removeSession(mUri.toString());
333        mSessionManager.putErrorMessage(mPlaceHolderSession.outputUri, reason);
334        mSessionManager.notifyTaskFailed(mPlaceHolderSession.outputUri, reason);
335    }
336
337    @Override
338    public void addProgressListener(ProgressListener listener) {
339        listener.onStatusMessageChanged(mProgressMessage);
340        listener.onProgressChanged(mProgressPercent);
341        mProgressListeners.add(listener);
342    }
343
344    @Override
345    public void removeProgressListener(ProgressListener listener) {
346        mProgressListeners.remove(listener);
347    }
348
349    private void onPreviewAvailable() {
350        mSessionManager.notifySessionPreviewAvailable(mPlaceHolderSession.outputUri);
351    }
352
353    private boolean isStarted() {
354        return mUri != null;
355    }
356}
357