StagefrightRecorder.cpp revision f95ce6452d87316b8f5df6692537bd039377f349
1/*
2 * Copyright (C) 2009 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
17//#define LOG_NDEBUG 0
18#define LOG_TAG "StagefrightRecorder"
19#include <utils/Log.h>
20
21#include "StagefrightRecorder.h"
22
23#include <binder/IPCThreadState.h>
24#include <media/stagefright/AudioSource.h>
25#include <media/stagefright/AMRWriter.h>
26#include <media/stagefright/CameraSource.h>
27#include <media/stagefright/CameraSourceTimeLapse.h>
28#include <media/stagefright/MPEG4Writer.h>
29#include <media/stagefright/MediaDebug.h>
30#include <media/stagefright/MediaDefs.h>
31#include <media/stagefright/MetaData.h>
32#include <media/stagefright/OMXClient.h>
33#include <media/stagefright/OMXCodec.h>
34#include <media/MediaProfiles.h>
35#include <camera/ICamera.h>
36#include <camera/Camera.h>
37#include <camera/CameraParameters.h>
38#include <surfaceflinger/ISurface.h>
39#include <utils/Errors.h>
40#include <sys/types.h>
41#include <unistd.h>
42#include <ctype.h>
43
44namespace android {
45
46StagefrightRecorder::StagefrightRecorder()
47    : mWriter(NULL),
48      mOutputFd(-1) {
49
50    LOGV("Constructor");
51    reset();
52}
53
54StagefrightRecorder::~StagefrightRecorder() {
55    LOGV("Destructor");
56    stop();
57
58    if (mOutputFd >= 0) {
59        ::close(mOutputFd);
60        mOutputFd = -1;
61    }
62}
63
64status_t StagefrightRecorder::init() {
65    LOGV("init");
66    return OK;
67}
68
69status_t StagefrightRecorder::setAudioSource(audio_source as) {
70    LOGV("setAudioSource: %d", as);
71    if (as < AUDIO_SOURCE_DEFAULT ||
72        as >= AUDIO_SOURCE_LIST_END) {
73        LOGE("Invalid audio source: %d", as);
74        return BAD_VALUE;
75    }
76
77    if (as == AUDIO_SOURCE_DEFAULT) {
78        mAudioSource = AUDIO_SOURCE_MIC;
79    } else {
80        mAudioSource = as;
81    }
82
83    return OK;
84}
85
86status_t StagefrightRecorder::setVideoSource(video_source vs) {
87    LOGV("setVideoSource: %d", vs);
88    if (vs < VIDEO_SOURCE_DEFAULT ||
89        vs >= VIDEO_SOURCE_LIST_END) {
90        LOGE("Invalid video source: %d", vs);
91        return BAD_VALUE;
92    }
93
94    if (vs == VIDEO_SOURCE_DEFAULT) {
95        mVideoSource = VIDEO_SOURCE_CAMERA;
96    } else {
97        mVideoSource = vs;
98    }
99
100    return OK;
101}
102
103status_t StagefrightRecorder::setOutputFormat(output_format of) {
104    LOGV("setOutputFormat: %d", of);
105    if (of < OUTPUT_FORMAT_DEFAULT ||
106        of >= OUTPUT_FORMAT_LIST_END) {
107        LOGE("Invalid output format: %d", of);
108        return BAD_VALUE;
109    }
110
111    if (of == OUTPUT_FORMAT_DEFAULT) {
112        mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
113    } else {
114        mOutputFormat = of;
115    }
116
117    return OK;
118}
119
120status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
121    LOGV("setAudioEncoder: %d", ae);
122    if (ae < AUDIO_ENCODER_DEFAULT ||
123        ae >= AUDIO_ENCODER_LIST_END) {
124        LOGE("Invalid audio encoder: %d", ae);
125        return BAD_VALUE;
126    }
127
128    if (ae == AUDIO_ENCODER_DEFAULT) {
129        mAudioEncoder = AUDIO_ENCODER_AMR_NB;
130    } else {
131        mAudioEncoder = ae;
132    }
133
134    return OK;
135}
136
137status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
138    LOGV("setVideoEncoder: %d", ve);
139    if (ve < VIDEO_ENCODER_DEFAULT ||
140        ve >= VIDEO_ENCODER_LIST_END) {
141        LOGE("Invalid video encoder: %d", ve);
142        return BAD_VALUE;
143    }
144
145    if (ve == VIDEO_ENCODER_DEFAULT) {
146        mVideoEncoder = VIDEO_ENCODER_H263;
147    } else {
148        mVideoEncoder = ve;
149    }
150
151    return OK;
152}
153
154status_t StagefrightRecorder::setVideoSize(int width, int height) {
155    LOGV("setVideoSize: %dx%d", width, height);
156    if (width <= 0 || height <= 0) {
157        LOGE("Invalid video size: %dx%d", width, height);
158        return BAD_VALUE;
159    }
160
161    // Additional check on the dimension will be performed later
162    mVideoWidth = width;
163    mVideoHeight = height;
164
165    return OK;
166}
167
168status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
169    LOGV("setVideoFrameRate: %d", frames_per_second);
170    if (frames_per_second <= 0 || frames_per_second > 30) {
171        LOGE("Invalid video frame rate: %d", frames_per_second);
172        return BAD_VALUE;
173    }
174
175    // Additional check on the frame rate will be performed later
176    mFrameRate = frames_per_second;
177
178    return OK;
179}
180
181status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) {
182    LOGV("setCamera");
183    if (camera == 0) {
184        LOGE("camera is NULL");
185        return BAD_VALUE;
186    }
187
188    int64_t token = IPCThreadState::self()->clearCallingIdentity();
189    mFlags &= ~FLAGS_HOT_CAMERA;
190    mCamera = Camera::create(camera);
191    if (mCamera == 0) {
192        LOGE("Unable to connect to camera");
193        IPCThreadState::self()->restoreCallingIdentity(token);
194        return -EBUSY;
195    }
196
197    LOGV("Connected to camera");
198    if (mCamera->previewEnabled()) {
199        LOGV("camera is hot");
200        mFlags |= FLAGS_HOT_CAMERA;
201    }
202    IPCThreadState::self()->restoreCallingIdentity(token);
203
204    return OK;
205}
206
207status_t StagefrightRecorder::setPreviewSurface(const sp<ISurface> &surface) {
208    LOGV("setPreviewSurface: %p", surface.get());
209    mPreviewSurface = surface;
210
211    return OK;
212}
213
214status_t StagefrightRecorder::setOutputFile(const char *path) {
215    LOGE("setOutputFile(const char*) must not be called");
216    // We don't actually support this at all, as the media_server process
217    // no longer has permissions to create files.
218
219    return -EPERM;
220}
221
222status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
223    LOGV("setOutputFile: %d, %lld, %lld", fd, offset, length);
224    // These don't make any sense, do they?
225    CHECK_EQ(offset, 0);
226    CHECK_EQ(length, 0);
227
228    if (fd < 0) {
229        LOGE("Invalid file descriptor: %d", fd);
230        return -EBADF;
231    }
232
233    if (mOutputFd >= 0) {
234        ::close(mOutputFd);
235    }
236    mOutputFd = dup(fd);
237
238    return OK;
239}
240
241// Attempt to parse an int64 literal optionally surrounded by whitespace,
242// returns true on success, false otherwise.
243static bool safe_strtoi64(const char *s, int64_t *val) {
244    char *end;
245    *val = strtoll(s, &end, 10);
246
247    if (end == s || errno == ERANGE) {
248        return false;
249    }
250
251    // Skip trailing whitespace
252    while (isspace(*end)) {
253        ++end;
254    }
255
256    // For a successful return, the string must contain nothing but a valid
257    // int64 literal optionally surrounded by whitespace.
258
259    return *end == '\0';
260}
261
262// Return true if the value is in [0, 0x007FFFFFFF]
263static bool safe_strtoi32(const char *s, int32_t *val) {
264    int64_t temp;
265    if (safe_strtoi64(s, &temp)) {
266        if (temp >= 0 && temp <= 0x007FFFFFFF) {
267            *val = static_cast<int32_t>(temp);
268            return true;
269        }
270    }
271    return false;
272}
273
274// Trim both leading and trailing whitespace from the given string.
275static void TrimString(String8 *s) {
276    size_t num_bytes = s->bytes();
277    const char *data = s->string();
278
279    size_t leading_space = 0;
280    while (leading_space < num_bytes && isspace(data[leading_space])) {
281        ++leading_space;
282    }
283
284    size_t i = num_bytes;
285    while (i > leading_space && isspace(data[i - 1])) {
286        --i;
287    }
288
289    s->setTo(String8(&data[leading_space], i - leading_space));
290}
291
292status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
293    LOGV("setParamAudioSamplingRate: %d", sampleRate);
294    if (sampleRate <= 0) {
295        LOGE("Invalid audio sampling rate: %d", sampleRate);
296        return BAD_VALUE;
297    }
298
299    // Additional check on the sample rate will be performed later.
300    mSampleRate = sampleRate;
301    return OK;
302}
303
304status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
305    LOGV("setParamAudioNumberOfChannels: %d", channels);
306    if (channels <= 0 || channels >= 3) {
307        LOGE("Invalid number of audio channels: %d", channels);
308        return BAD_VALUE;
309    }
310
311    // Additional check on the number of channels will be performed later.
312    mAudioChannels = channels;
313    return OK;
314}
315
316status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
317    LOGV("setParamAudioEncodingBitRate: %d", bitRate);
318    if (bitRate <= 0) {
319        LOGE("Invalid audio encoding bit rate: %d", bitRate);
320        return BAD_VALUE;
321    }
322
323    // The target bit rate may not be exactly the same as the requested.
324    // It depends on many factors, such as rate control, and the bit rate
325    // range that a specific encoder supports. The mismatch between the
326    // the target and requested bit rate will NOT be treated as an error.
327    mAudioBitRate = bitRate;
328    return OK;
329}
330
331status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
332    LOGV("setParamVideoEncodingBitRate: %d", bitRate);
333    if (bitRate <= 0) {
334        LOGE("Invalid video encoding bit rate: %d", bitRate);
335        return BAD_VALUE;
336    }
337
338    // The target bit rate may not be exactly the same as the requested.
339    // It depends on many factors, such as rate control, and the bit rate
340    // range that a specific encoder supports. The mismatch between the
341    // the target and requested bit rate will NOT be treated as an error.
342    mVideoBitRate = bitRate;
343    return OK;
344}
345
346status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
347    LOGV("setParamMaxFileDurationUs: %lld us", timeUs);
348    if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
349        LOGE("Max file duration is too short: %lld us", timeUs);
350        return BAD_VALUE;
351    }
352    mMaxFileDurationUs = timeUs;
353    return OK;
354}
355
356status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
357    LOGV("setParamMaxFileSizeBytes: %lld bytes", bytes);
358    if (bytes <= 1024) {  // XXX: 1 kB
359        LOGE("Max file size is too small: %lld bytes", bytes);
360        return BAD_VALUE;
361    }
362    mMaxFileSizeBytes = bytes;
363    return OK;
364}
365
366status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
367    LOGV("setParamInterleaveDuration: %d", durationUs);
368    if (durationUs <= 500000) {           //  500 ms
369        // If interleave duration is too small, it is very inefficient to do
370        // interleaving since the metadata overhead will count for a significant
371        // portion of the saved contents
372        LOGE("Audio/video interleave duration is too small: %d us", durationUs);
373        return BAD_VALUE;
374    } else if (durationUs >= 10000000) {  // 10 seconds
375        // If interleaving duration is too large, it can cause the recording
376        // session to use too much memory since we have to save the output
377        // data before we write them out
378        LOGE("Audio/video interleave duration is too large: %d us", durationUs);
379        return BAD_VALUE;
380    }
381    mInterleaveDurationUs = durationUs;
382    return OK;
383}
384
385// If seconds <  0, only the first frame is I frame, and rest are all P frames
386// If seconds == 0, all frames are encoded as I frames. No P frames
387// If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
388status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
389    LOGV("setParamVideoIFramesInterval: %d seconds", seconds);
390    mIFramesIntervalSec = seconds;
391    return OK;
392}
393
394status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
395    LOGV("setParam64BitFileOffset: %s",
396        use64Bit? "use 64 bit file offset": "use 32 bit file offset");
397    mUse64BitFileOffset = use64Bit;
398    return OK;
399}
400
401status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
402    LOGV("setParamVideoCameraId: %d", cameraId);
403    if (cameraId < 0) {
404        return BAD_VALUE;
405    }
406    mCameraId = cameraId;
407    return OK;
408}
409
410status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
411    LOGV("setParamTrackTimeStatus: %lld", timeDurationUs);
412    if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
413        LOGE("Tracking time duration too short: %lld us", timeDurationUs);
414        return BAD_VALUE;
415    }
416    mTrackEveryTimeDurationUs = timeDurationUs;
417    return OK;
418}
419
420status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
421    LOGV("setParamVideoEncoderProfile: %d", profile);
422
423    // Additional check will be done later when we load the encoder.
424    // For now, we are accepting values defined in OpenMAX IL.
425    mVideoEncoderProfile = profile;
426    return OK;
427}
428
429status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
430    LOGV("setParamVideoEncoderLevel: %d", level);
431
432    // Additional check will be done later when we load the encoder.
433    // For now, we are accepting values defined in OpenMAX IL.
434    mVideoEncoderLevel = level;
435    return OK;
436}
437
438status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
439    LOGV("setParamMovieTimeScale: %d", timeScale);
440
441    // The range is set to be the same as the audio's time scale range
442    // since audio's time scale has a wider range.
443    if (timeScale < 600 || timeScale > 96000) {
444        LOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
445        return BAD_VALUE;
446    }
447    mMovieTimeScale = timeScale;
448    return OK;
449}
450
451status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
452    LOGV("setParamVideoTimeScale: %d", timeScale);
453
454    // 60000 is chosen to make sure that each video frame from a 60-fps
455    // video has 1000 ticks.
456    if (timeScale < 600 || timeScale > 60000) {
457        LOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
458        return BAD_VALUE;
459    }
460    mVideoTimeScale = timeScale;
461    return OK;
462}
463
464status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
465    LOGV("setParamAudioTimeScale: %d", timeScale);
466
467    // 96000 Hz is the highest sampling rate support in AAC.
468    if (timeScale < 600 || timeScale > 96000) {
469        LOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
470        return BAD_VALUE;
471    }
472    mAudioTimeScale = timeScale;
473    return OK;
474}
475
476status_t StagefrightRecorder::setParamTimeLapseEnable(int32_t timeLapseEnable) {
477    LOGV("setParamTimeLapseEnable: %d", timeLapseEnable);
478
479    if(timeLapseEnable == 0) {
480        mCaptureTimeLapse = false;
481    } else if (timeLapseEnable == 1) {
482        mCaptureTimeLapse = true;
483    } else {
484        return BAD_VALUE;
485    }
486    return OK;
487}
488
489status_t StagefrightRecorder::setParamUseStillCameraForTimeLapse(int32_t useStillCamera) {
490    LOGV("setParamUseStillCameraForTimeLapse: %d", useStillCamera);
491
492    if(useStillCamera == 0) {
493        mUseStillCameraForTimeLapse= false;
494    } else if (useStillCamera == 1) {
495        mUseStillCameraForTimeLapse= true;
496    } else {
497        return BAD_VALUE;
498    }
499    return OK;
500}
501
502status_t StagefrightRecorder::setParamTimeBetweenTimeLapseFrameCapture(int64_t timeUs) {
503    LOGV("setParamTimeBetweenTimeLapseFrameCapture: %lld us", timeUs);
504
505    // Not allowing time more than a day
506    if (timeUs <= 0 || timeUs > 86400*1E6) {
507        LOGE("Time between time lapse frame capture (%lld) is out of range [0, 1 Day]", timeUs);
508        return BAD_VALUE;
509    }
510
511    mTimeBetweenTimeLapseFrameCaptureUs = timeUs;
512    return OK;
513}
514
515status_t StagefrightRecorder::setParameter(
516        const String8 &key, const String8 &value) {
517    LOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
518    if (key == "max-duration") {
519        int64_t max_duration_ms;
520        if (safe_strtoi64(value.string(), &max_duration_ms)) {
521            return setParamMaxFileDurationUs(1000LL * max_duration_ms);
522        }
523    } else if (key == "max-filesize") {
524        int64_t max_filesize_bytes;
525        if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
526            return setParamMaxFileSizeBytes(max_filesize_bytes);
527        }
528    } else if (key == "interleave-duration-us") {
529        int32_t durationUs;
530        if (safe_strtoi32(value.string(), &durationUs)) {
531            return setParamInterleaveDuration(durationUs);
532        }
533    } else if (key == "param-movie-time-scale") {
534        int32_t timeScale;
535        if (safe_strtoi32(value.string(), &timeScale)) {
536            return setParamMovieTimeScale(timeScale);
537        }
538    } else if (key == "param-use-64bit-offset") {
539        int32_t use64BitOffset;
540        if (safe_strtoi32(value.string(), &use64BitOffset)) {
541            return setParam64BitFileOffset(use64BitOffset != 0);
542        }
543    } else if (key == "param-track-time-status") {
544        int64_t timeDurationUs;
545        if (safe_strtoi64(value.string(), &timeDurationUs)) {
546            return setParamTrackTimeStatus(timeDurationUs);
547        }
548    } else if (key == "audio-param-sampling-rate") {
549        int32_t sampling_rate;
550        if (safe_strtoi32(value.string(), &sampling_rate)) {
551            return setParamAudioSamplingRate(sampling_rate);
552        }
553    } else if (key == "audio-param-number-of-channels") {
554        int32_t number_of_channels;
555        if (safe_strtoi32(value.string(), &number_of_channels)) {
556            return setParamAudioNumberOfChannels(number_of_channels);
557        }
558    } else if (key == "audio-param-encoding-bitrate") {
559        int32_t audio_bitrate;
560        if (safe_strtoi32(value.string(), &audio_bitrate)) {
561            return setParamAudioEncodingBitRate(audio_bitrate);
562        }
563    } else if (key == "audio-param-time-scale") {
564        int32_t timeScale;
565        if (safe_strtoi32(value.string(), &timeScale)) {
566            return setParamAudioTimeScale(timeScale);
567        }
568    } else if (key == "video-param-encoding-bitrate") {
569        int32_t video_bitrate;
570        if (safe_strtoi32(value.string(), &video_bitrate)) {
571            return setParamVideoEncodingBitRate(video_bitrate);
572        }
573    } else if (key == "video-param-i-frames-interval") {
574        int32_t seconds;
575        if (safe_strtoi32(value.string(), &seconds)) {
576            return setParamVideoIFramesInterval(seconds);
577        }
578    } else if (key == "video-param-encoder-profile") {
579        int32_t profile;
580        if (safe_strtoi32(value.string(), &profile)) {
581            return setParamVideoEncoderProfile(profile);
582        }
583    } else if (key == "video-param-encoder-level") {
584        int32_t level;
585        if (safe_strtoi32(value.string(), &level)) {
586            return setParamVideoEncoderLevel(level);
587        }
588    } else if (key == "video-param-camera-id") {
589        int32_t cameraId;
590        if (safe_strtoi32(value.string(), &cameraId)) {
591            return setParamVideoCameraId(cameraId);
592        }
593    } else if (key == "video-param-time-scale") {
594        int32_t timeScale;
595        if (safe_strtoi32(value.string(), &timeScale)) {
596            return setParamVideoTimeScale(timeScale);
597        }
598    } else if (key == "time-lapse-enable") {
599        int32_t timeLapseEnable;
600        if (safe_strtoi32(value.string(), &timeLapseEnable)) {
601            return setParamTimeLapseEnable(timeLapseEnable);
602        }
603    } else if (key == "use-still-camera-for-time-lapse") {
604        int32_t useStillCamera;
605        if (safe_strtoi32(value.string(), &useStillCamera)) {
606            return setParamUseStillCameraForTimeLapse(useStillCamera);
607        }
608    } else if (key == "time-between-time-lapse-frame-capture") {
609        int64_t timeBetweenTimeLapseFrameCaptureMs;
610        if (safe_strtoi64(value.string(), &timeBetweenTimeLapseFrameCaptureMs)) {
611            return setParamTimeBetweenTimeLapseFrameCapture(
612                    1000LL * timeBetweenTimeLapseFrameCaptureMs);
613        }
614    } else {
615        LOGE("setParameter: failed to find key %s", key.string());
616    }
617    return BAD_VALUE;
618}
619
620status_t StagefrightRecorder::setParameters(const String8 &params) {
621    LOGV("setParameters: %s", params.string());
622    const char *cparams = params.string();
623    const char *key_start = cparams;
624    for (;;) {
625        const char *equal_pos = strchr(key_start, '=');
626        if (equal_pos == NULL) {
627            LOGE("Parameters %s miss a value", cparams);
628            return BAD_VALUE;
629        }
630        String8 key(key_start, equal_pos - key_start);
631        TrimString(&key);
632        if (key.length() == 0) {
633            LOGE("Parameters %s contains an empty key", cparams);
634            return BAD_VALUE;
635        }
636        const char *value_start = equal_pos + 1;
637        const char *semicolon_pos = strchr(value_start, ';');
638        String8 value;
639        if (semicolon_pos == NULL) {
640            value.setTo(value_start);
641        } else {
642            value.setTo(value_start, semicolon_pos - value_start);
643        }
644        if (setParameter(key, value) != OK) {
645            return BAD_VALUE;
646        }
647        if (semicolon_pos == NULL) {
648            break;  // Reaches the end
649        }
650        key_start = semicolon_pos + 1;
651    }
652    return OK;
653}
654
655status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
656    mListener = listener;
657
658    return OK;
659}
660
661status_t StagefrightRecorder::prepare() {
662    return OK;
663}
664
665status_t StagefrightRecorder::start() {
666    CHECK(mOutputFd >= 0);
667
668    if (mWriter != NULL) {
669        LOGE("File writer is not avaialble");
670        return UNKNOWN_ERROR;
671    }
672
673    switch (mOutputFormat) {
674        case OUTPUT_FORMAT_DEFAULT:
675        case OUTPUT_FORMAT_THREE_GPP:
676        case OUTPUT_FORMAT_MPEG_4:
677            return startMPEG4Recording();
678
679        case OUTPUT_FORMAT_AMR_NB:
680        case OUTPUT_FORMAT_AMR_WB:
681            return startAMRRecording();
682
683        case OUTPUT_FORMAT_AAC_ADIF:
684        case OUTPUT_FORMAT_AAC_ADTS:
685            return startAACRecording();
686
687        default:
688            LOGE("Unsupported output file format: %d", mOutputFormat);
689            return UNKNOWN_ERROR;
690    }
691}
692
693sp<MediaSource> StagefrightRecorder::createAudioSource() {
694    sp<AudioSource> audioSource =
695        new AudioSource(
696                mAudioSource,
697                mSampleRate,
698                mAudioChannels);
699
700    status_t err = audioSource->initCheck();
701
702    if (err != OK) {
703        LOGE("audio source is not initialized");
704        return NULL;
705    }
706
707    sp<MetaData> encMeta = new MetaData;
708    const char *mime;
709    switch (mAudioEncoder) {
710        case AUDIO_ENCODER_AMR_NB:
711        case AUDIO_ENCODER_DEFAULT:
712            mime = MEDIA_MIMETYPE_AUDIO_AMR_NB;
713            break;
714        case AUDIO_ENCODER_AMR_WB:
715            mime = MEDIA_MIMETYPE_AUDIO_AMR_WB;
716            break;
717        case AUDIO_ENCODER_AAC:
718            mime = MEDIA_MIMETYPE_AUDIO_AAC;
719            break;
720        default:
721            LOGE("Unknown audio encoder: %d", mAudioEncoder);
722            return NULL;
723    }
724    encMeta->setCString(kKeyMIMEType, mime);
725
726    int32_t maxInputSize;
727    CHECK(audioSource->getFormat()->findInt32(
728                kKeyMaxInputSize, &maxInputSize));
729
730    encMeta->setInt32(kKeyMaxInputSize, maxInputSize);
731    encMeta->setInt32(kKeyChannelCount, mAudioChannels);
732    encMeta->setInt32(kKeySampleRate, mSampleRate);
733    encMeta->setInt32(kKeyBitRate, mAudioBitRate);
734    encMeta->setInt32(kKeyTimeScale, mAudioTimeScale);
735
736    OMXClient client;
737    CHECK_EQ(client.connect(), OK);
738
739    sp<MediaSource> audioEncoder =
740        OMXCodec::Create(client.interface(), encMeta,
741                         true /* createEncoder */, audioSource);
742    mAudioSourceNode = audioSource;
743
744    return audioEncoder;
745}
746
747status_t StagefrightRecorder::startAACRecording() {
748    CHECK(mOutputFormat == OUTPUT_FORMAT_AAC_ADIF ||
749          mOutputFormat == OUTPUT_FORMAT_AAC_ADTS);
750
751    CHECK(mAudioEncoder == AUDIO_ENCODER_AAC);
752    CHECK(mAudioSource != AUDIO_SOURCE_LIST_END);
753
754    CHECK(0 == "AACWriter is not implemented yet");
755
756    return OK;
757}
758
759status_t StagefrightRecorder::startAMRRecording() {
760    CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
761          mOutputFormat == OUTPUT_FORMAT_AMR_WB);
762
763    if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
764        if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
765            mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
766            LOGE("Invalid encoder %d used for AMRNB recording",
767                    mAudioEncoder);
768            return BAD_VALUE;
769        }
770        if (mSampleRate != 8000) {
771            LOGE("Invalid sampling rate %d used for AMRNB recording",
772                    mSampleRate);
773            return BAD_VALUE;
774        }
775    } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
776        if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
777            LOGE("Invlaid encoder %d used for AMRWB recording",
778                    mAudioEncoder);
779            return BAD_VALUE;
780        }
781        if (mSampleRate != 16000) {
782            LOGE("Invalid sample rate %d used for AMRWB recording",
783                    mSampleRate);
784            return BAD_VALUE;
785        }
786    }
787    if (mAudioChannels != 1) {
788        LOGE("Invalid number of audio channels %d used for amr recording",
789                mAudioChannels);
790        return BAD_VALUE;
791    }
792
793    if (mAudioSource >= AUDIO_SOURCE_LIST_END) {
794        LOGE("Invalid audio source: %d", mAudioSource);
795        return BAD_VALUE;
796    }
797
798    sp<MediaSource> audioEncoder = createAudioSource();
799
800    if (audioEncoder == NULL) {
801        return UNKNOWN_ERROR;
802    }
803
804    mWriter = new AMRWriter(dup(mOutputFd));
805    mWriter->addSource(audioEncoder);
806
807    if (mMaxFileDurationUs != 0) {
808        mWriter->setMaxFileDuration(mMaxFileDurationUs);
809    }
810    if (mMaxFileSizeBytes != 0) {
811        mWriter->setMaxFileSize(mMaxFileSizeBytes);
812    }
813    mWriter->setListener(mListener);
814    mWriter->start();
815
816    return OK;
817}
818
819void StagefrightRecorder::clipVideoFrameRate() {
820    LOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
821    int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
822                        "enc.vid.fps.min", mVideoEncoder);
823    int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
824                        "enc.vid.fps.max", mVideoEncoder);
825    if (mFrameRate < minFrameRate) {
826        LOGW("Intended video encoding frame rate (%d fps) is too small"
827             " and will be set to (%d fps)", mFrameRate, minFrameRate);
828        mFrameRate = minFrameRate;
829    } else if (mFrameRate > maxFrameRate) {
830        LOGW("Intended video encoding frame rate (%d fps) is too large"
831             " and will be set to (%d fps)", mFrameRate, maxFrameRate);
832        mFrameRate = maxFrameRate;
833    }
834}
835
836void StagefrightRecorder::clipVideoBitRate() {
837    LOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
838    int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
839                        "enc.vid.bps.min", mVideoEncoder);
840    int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
841                        "enc.vid.bps.max", mVideoEncoder);
842    if (mVideoBitRate < minBitRate) {
843        LOGW("Intended video encoding bit rate (%d bps) is too small"
844             " and will be set to (%d bps)", mVideoBitRate, minBitRate);
845        mVideoBitRate = minBitRate;
846    } else if (mVideoBitRate > maxBitRate) {
847        LOGW("Intended video encoding bit rate (%d bps) is too large"
848             " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
849        mVideoBitRate = maxBitRate;
850    }
851}
852
853void StagefrightRecorder::clipVideoFrameWidth() {
854    LOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
855    int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
856                        "enc.vid.width.min", mVideoEncoder);
857    int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
858                        "enc.vid.width.max", mVideoEncoder);
859    if (mVideoWidth < minFrameWidth) {
860        LOGW("Intended video encoding frame width (%d) is too small"
861             " and will be set to (%d)", mVideoWidth, minFrameWidth);
862        mVideoWidth = minFrameWidth;
863    } else if (mVideoWidth > maxFrameWidth) {
864        LOGW("Intended video encoding frame width (%d) is too large"
865             " and will be set to (%d)", mVideoWidth, maxFrameWidth);
866        mVideoWidth = maxFrameWidth;
867    }
868}
869
870status_t StagefrightRecorder::setupCameraSource() {
871    if(!mCaptureTimeLapse) {
872        // Dont clip for time lapse capture as encoder will have enough
873        // time to encode because of slow capture rate of time lapse.
874        clipVideoBitRate();
875        clipVideoFrameRate();
876        clipVideoFrameWidth();
877        clipVideoFrameHeight();
878    }
879
880    int64_t token = IPCThreadState::self()->clearCallingIdentity();
881    if (mCamera == 0) {
882        mCamera = Camera::connect(mCameraId);
883        if (mCamera == 0) {
884            LOGE("Camera connection could not be established.");
885            return -EBUSY;
886        }
887        mFlags &= ~FLAGS_HOT_CAMERA;
888        mCamera->lock();
889    }
890
891    // Set the actual video recording frame size
892    CameraParameters params(mCamera->getParameters());
893
894    // dont change the preview size for time lapse as mVideoWidth, mVideoHeight
895    // may correspond to HD resolution not supported by video camera.
896    if (!mCaptureTimeLapse) {
897        params.setPreviewSize(mVideoWidth, mVideoHeight);
898    }
899
900    params.setPreviewFrameRate(mFrameRate);
901    String8 s = params.flatten();
902    CHECK_EQ(OK, mCamera->setParameters(s));
903    CameraParameters newCameraParams(mCamera->getParameters());
904
905    // Check on video frame size
906    int frameWidth = 0, frameHeight = 0;
907    newCameraParams.getPreviewSize(&frameWidth, &frameHeight);
908    if (!mCaptureTimeLapse &&
909        (frameWidth  < 0 || frameWidth  != mVideoWidth ||
910        frameHeight < 0 || frameHeight != mVideoHeight)) {
911        LOGE("Failed to set the video frame size to %dx%d",
912                mVideoWidth, mVideoHeight);
913        IPCThreadState::self()->restoreCallingIdentity(token);
914        return UNKNOWN_ERROR;
915    }
916
917    // Check on video frame rate
918    int frameRate = newCameraParams.getPreviewFrameRate();
919    if (frameRate < 0 || (frameRate - mFrameRate) != 0) {
920        LOGE("Failed to set frame rate to %d fps. The actual "
921             "frame rate is %d", mFrameRate, frameRate);
922    }
923
924    CHECK_EQ(OK, mCamera->setPreviewDisplay(mPreviewSurface));
925    IPCThreadState::self()->restoreCallingIdentity(token);
926    return OK;
927}
928
929void StagefrightRecorder::clipVideoFrameHeight() {
930    LOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
931    int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
932                        "enc.vid.height.min", mVideoEncoder);
933    int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
934                        "enc.vid.height.max", mVideoEncoder);
935    if (mVideoHeight < minFrameHeight) {
936        LOGW("Intended video encoding frame height (%d) is too small"
937             " and will be set to (%d)", mVideoHeight, minFrameHeight);
938        mVideoHeight = minFrameHeight;
939    } else if (mVideoHeight > maxFrameHeight) {
940        LOGW("Intended video encoding frame height (%d) is too large"
941             " and will be set to (%d)", mVideoHeight, maxFrameHeight);
942        mVideoHeight = maxFrameHeight;
943    }
944}
945
946status_t StagefrightRecorder::setupVideoEncoder(const sp<MediaWriter>& writer) {
947    status_t err = setupCameraSource();
948    if (err != OK) return err;
949
950    sp<CameraSource> cameraSource = (mCaptureTimeLapse) ?
951        CameraSourceTimeLapse::CreateFromCamera(mCamera, mUseStillCameraForTimeLapse,
952                mTimeBetweenTimeLapseFrameCaptureUs, mVideoWidth, mVideoHeight, mFrameRate):
953        CameraSource::CreateFromCamera(mCamera);
954    CHECK(cameraSource != NULL);
955
956    sp<MetaData> enc_meta = new MetaData;
957    enc_meta->setInt32(kKeyBitRate, mVideoBitRate);
958    enc_meta->setInt32(kKeySampleRate, mFrameRate);
959
960    switch (mVideoEncoder) {
961        case VIDEO_ENCODER_H263:
962            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
963            break;
964
965        case VIDEO_ENCODER_MPEG_4_SP:
966            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
967            break;
968
969        case VIDEO_ENCODER_H264:
970            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
971            break;
972
973        default:
974            CHECK(!"Should not be here, unsupported video encoding.");
975            break;
976    }
977
978    sp<MetaData> meta = cameraSource->getFormat();
979
980    int32_t width, height, stride, sliceHeight, colorFormat;
981    CHECK(meta->findInt32(kKeyWidth, &width));
982    CHECK(meta->findInt32(kKeyHeight, &height));
983    CHECK(meta->findInt32(kKeyStride, &stride));
984    CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
985    CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
986
987    enc_meta->setInt32(kKeyWidth, width);
988    enc_meta->setInt32(kKeyHeight, height);
989    enc_meta->setInt32(kKeyIFramesInterval, mIFramesIntervalSec);
990    enc_meta->setInt32(kKeyStride, stride);
991    enc_meta->setInt32(kKeySliceHeight, sliceHeight);
992    enc_meta->setInt32(kKeyColorFormat, colorFormat);
993    enc_meta->setInt32(kKeyTimeScale, mVideoTimeScale);
994    if (mVideoEncoderProfile != -1) {
995        enc_meta->setInt32(kKeyVideoProfile, mVideoEncoderProfile);
996    }
997    if (mVideoEncoderLevel != -1) {
998        enc_meta->setInt32(kKeyVideoLevel, mVideoEncoderLevel);
999    }
1000
1001    OMXClient client;
1002    CHECK_EQ(client.connect(), OK);
1003
1004    // Use software codec for time lapse
1005    uint32_t encoder_flags = (mCaptureTimeLapse) ? OMXCodec::kPreferSoftwareCodecs : 0;
1006    sp<MediaSource> encoder = OMXCodec::Create(
1007            client.interface(), enc_meta,
1008            true /* createEncoder */, cameraSource,
1009            NULL, encoder_flags);
1010    if (encoder == NULL) {
1011        return UNKNOWN_ERROR;
1012    }
1013
1014    writer->addSource(encoder);
1015    return OK;
1016}
1017
1018status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1019    sp<MediaSource> audioEncoder;
1020    switch(mAudioEncoder) {
1021        case AUDIO_ENCODER_AMR_NB:
1022        case AUDIO_ENCODER_AMR_WB:
1023        case AUDIO_ENCODER_AAC:
1024            audioEncoder = createAudioSource();
1025            break;
1026        default:
1027            LOGE("Unsupported audio encoder: %d", mAudioEncoder);
1028            return UNKNOWN_ERROR;
1029    }
1030
1031    if (audioEncoder == NULL) {
1032        return UNKNOWN_ERROR;
1033    }
1034
1035    writer->addSource(audioEncoder);
1036    return OK;
1037}
1038
1039status_t StagefrightRecorder::startMPEG4Recording() {
1040    int32_t totalBitRate = 0;
1041    status_t err = OK;
1042    sp<MediaWriter> writer = new MPEG4Writer(dup(mOutputFd));
1043
1044    // Add audio source first if it exists
1045    if (!mCaptureTimeLapse && (mAudioSource != AUDIO_SOURCE_LIST_END)) {
1046        err = setupAudioEncoder(writer);
1047        if (err != OK) return err;
1048        totalBitRate += mAudioBitRate;
1049    }
1050    if (mVideoSource == VIDEO_SOURCE_DEFAULT
1051            || mVideoSource == VIDEO_SOURCE_CAMERA) {
1052        err = setupVideoEncoder(writer);
1053        if (err != OK) return err;
1054        totalBitRate += mVideoBitRate;
1055    }
1056
1057    if (mInterleaveDurationUs > 0) {
1058        reinterpret_cast<MPEG4Writer *>(writer.get())->
1059            setInterleaveDuration(mInterleaveDurationUs);
1060    }
1061
1062    if (mMaxFileDurationUs != 0) {
1063        writer->setMaxFileDuration(mMaxFileDurationUs);
1064    }
1065    if (mMaxFileSizeBytes != 0) {
1066        writer->setMaxFileSize(mMaxFileSizeBytes);
1067    }
1068    sp<MetaData> meta = new MetaData;
1069    meta->setInt64(kKeyTime, systemTime() / 1000);
1070    meta->setInt32(kKeyFileType, mOutputFormat);
1071    meta->setInt32(kKeyBitRate, totalBitRate);
1072    meta->setInt32(kKey64BitFileOffset, mUse64BitFileOffset);
1073    meta->setInt32(kKeyTimeScale, mMovieTimeScale);
1074    if (mTrackEveryTimeDurationUs > 0) {
1075        meta->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
1076    }
1077    writer->setListener(mListener);
1078    mWriter = writer;
1079    return mWriter->start(meta.get());
1080}
1081
1082status_t StagefrightRecorder::pause() {
1083    LOGV("pause");
1084    if (mWriter == NULL) {
1085        return UNKNOWN_ERROR;
1086    }
1087    mWriter->pause();
1088    return OK;
1089}
1090
1091status_t StagefrightRecorder::stop() {
1092    LOGV("stop");
1093    if (mWriter != NULL) {
1094        mWriter->stop();
1095        mWriter.clear();
1096    }
1097
1098    if (mCamera != 0) {
1099        LOGV("Disconnect camera");
1100        int64_t token = IPCThreadState::self()->clearCallingIdentity();
1101        if ((mFlags & FLAGS_HOT_CAMERA) == 0) {
1102            LOGV("Camera was cold when we started, stopping preview");
1103            mCamera->stopPreview();
1104        }
1105        mCamera->unlock();
1106        mCamera.clear();
1107        IPCThreadState::self()->restoreCallingIdentity(token);
1108        mFlags = 0;
1109    }
1110
1111    return OK;
1112}
1113
1114status_t StagefrightRecorder::close() {
1115    LOGV("close");
1116    stop();
1117
1118    return OK;
1119}
1120
1121status_t StagefrightRecorder::reset() {
1122    LOGV("reset");
1123    stop();
1124
1125    // No audio or video source by default
1126    mAudioSource = AUDIO_SOURCE_LIST_END;
1127    mVideoSource = VIDEO_SOURCE_LIST_END;
1128
1129    // Default parameters
1130    mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
1131    mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
1132    mVideoEncoder  = VIDEO_ENCODER_H263;
1133    mVideoWidth    = 176;
1134    mVideoHeight   = 144;
1135    mFrameRate     = 20;
1136    mVideoBitRate  = 192000;
1137    mSampleRate    = 8000;
1138    mAudioChannels = 1;
1139    mAudioBitRate  = 12200;
1140    mInterleaveDurationUs = 0;
1141    mIFramesIntervalSec = 1;
1142    mAudioSourceNode = 0;
1143    mUse64BitFileOffset = false;
1144    mMovieTimeScale  = 1000;
1145    mAudioTimeScale  = 1000;
1146    mVideoTimeScale  = 1000;
1147    mCameraId        = 0;
1148    mVideoEncoderProfile = -1;
1149    mVideoEncoderLevel   = -1;
1150    mMaxFileDurationUs = 0;
1151    mMaxFileSizeBytes = 0;
1152    mTrackEveryTimeDurationUs = 0;
1153    mCaptureTimeLapse = false;
1154    mUseStillCameraForTimeLapse = true;
1155    mTimeBetweenTimeLapseFrameCaptureUs = -1;
1156    mEncoderProfiles = MediaProfiles::getInstance();
1157
1158    mOutputFd = -1;
1159    mFlags = 0;
1160
1161    return OK;
1162}
1163
1164status_t StagefrightRecorder::getMaxAmplitude(int *max) {
1165    LOGV("getMaxAmplitude");
1166
1167    if (max == NULL) {
1168        LOGE("Null pointer argument");
1169        return BAD_VALUE;
1170    }
1171
1172    if (mAudioSourceNode != 0) {
1173        *max = mAudioSourceNode->getMaxAmplitude();
1174    } else {
1175        *max = 0;
1176    }
1177
1178    return OK;
1179}
1180
1181status_t StagefrightRecorder::dump(int fd, const Vector<String16>& args) const {
1182    const size_t SIZE = 256;
1183    char buffer[SIZE];
1184    String8 result;
1185    snprintf(buffer, SIZE, "   Recorder: %p", this);
1186    snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
1187    result.append(buffer);
1188    snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
1189    result.append(buffer);
1190    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
1191    result.append(buffer);
1192    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
1193    result.append(buffer);
1194    snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
1195    result.append(buffer);
1196    snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
1197    result.append(buffer);
1198    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
1199    result.append(buffer);
1200    snprintf(buffer, SIZE, "   Audio\n");
1201    result.append(buffer);
1202    snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
1203    result.append(buffer);
1204    snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
1205    result.append(buffer);
1206    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
1207    result.append(buffer);
1208    snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
1209    result.append(buffer);
1210    snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
1211    result.append(buffer);
1212    snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
1213    result.append(buffer);
1214    snprintf(buffer, SIZE, "   Video\n");
1215    result.append(buffer);
1216    snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
1217    result.append(buffer);
1218    snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
1219    result.append(buffer);
1220    snprintf(buffer, SIZE, "     Camera flags: %d\n", mFlags);
1221    result.append(buffer);
1222    snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
1223    result.append(buffer);
1224    snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
1225    result.append(buffer);
1226    snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
1227    result.append(buffer);
1228    snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
1229    result.append(buffer);
1230    snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
1231    result.append(buffer);
1232    snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
1233    result.append(buffer);
1234    snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
1235    result.append(buffer);
1236    ::write(fd, result.string(), result.size());
1237    return OK;
1238}
1239}  // namespace android
1240