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 <inttypes.h>
20 #include <utils/Log.h>
21 
22 #include "WebmWriter.h"
23 #include "StagefrightRecorder.h"
24 
25 #include <algorithm>
26 
27 #include <android-base/properties.h>
28 #include <android/hardware/ICamera.h>
29 
30 #include <binder/IPCThreadState.h>
31 #include <binder/IServiceManager.h>
32 
33 #include <media/IMediaPlayerService.h>
34 #include <media/MediaMetricsItem.h>
35 #include <media/stagefright/foundation/ABuffer.h>
36 #include <media/stagefright/foundation/ADebug.h>
37 #include <media/stagefright/foundation/AMessage.h>
38 #include <media/stagefright/foundation/ALooper.h>
39 #include <media/stagefright/ACodec.h>
40 #include <media/stagefright/AudioSource.h>
41 #include <media/stagefright/AMRWriter.h>
42 #include <media/stagefright/AACWriter.h>
43 #include <media/stagefright/CameraSource.h>
44 #include <media/stagefright/CameraSourceTimeLapse.h>
45 #include <media/stagefright/MPEG2TSWriter.h>
46 #include <media/stagefright/MPEG4Writer.h>
47 #include <media/stagefright/MediaDefs.h>
48 #include <media/stagefright/MetaData.h>
49 #include <media/stagefright/MediaCodecSource.h>
50 #include <media/stagefright/OggWriter.h>
51 #include <media/stagefright/PersistentSurface.h>
52 #include <media/MediaProfiles.h>
53 #include <camera/CameraParameters.h>
54 
55 #include <utils/Errors.h>
56 #include <sys/types.h>
57 #include <ctype.h>
58 #include <unistd.h>
59 
60 #include <system/audio.h>
61 
62 #include "ARTPWriter.h"
63 
64 namespace android {
65 
66 static const float kTypicalDisplayRefreshingRate = 60.f;
67 // display refresh rate drops on battery saver
68 static const float kMinTypicalDisplayRefreshingRate = kTypicalDisplayRefreshingRate / 2;
69 static const int kMaxNumVideoTemporalLayers = 8;
70 
71 // key for media statistics
72 static const char *kKeyRecorder = "recorder";
73 // attrs for media statistics
74 // NB: these are matched with public Java API constants defined
75 // in frameworks/base/media/java/android/media/MediaRecorder.java
76 // These must be kept synchronized with the constants there.
77 static const char *kRecorderAudioBitrate = "android.media.mediarecorder.audio-bitrate";
78 static const char *kRecorderAudioChannels = "android.media.mediarecorder.audio-channels";
79 static const char *kRecorderAudioSampleRate = "android.media.mediarecorder.audio-samplerate";
80 static const char *kRecorderAudioTimescale = "android.media.mediarecorder.audio-timescale";
81 static const char *kRecorderCaptureFps = "android.media.mediarecorder.capture-fps";
82 static const char *kRecorderCaptureFpsEnable = "android.media.mediarecorder.capture-fpsenable";
83 static const char *kRecorderFrameRate = "android.media.mediarecorder.frame-rate";
84 static const char *kRecorderHeight = "android.media.mediarecorder.height";
85 static const char *kRecorderMovieTimescale = "android.media.mediarecorder.movie-timescale";
86 static const char *kRecorderRotation = "android.media.mediarecorder.rotation";
87 static const char *kRecorderVideoBitrate = "android.media.mediarecorder.video-bitrate";
88 static const char *kRecorderVideoIframeInterval = "android.media.mediarecorder.video-iframe-interval";
89 static const char *kRecorderVideoLevel = "android.media.mediarecorder.video-encoder-level";
90 static const char *kRecorderVideoProfile = "android.media.mediarecorder.video-encoder-profile";
91 static const char *kRecorderVideoTimescale = "android.media.mediarecorder.video-timescale";
92 static const char *kRecorderWidth = "android.media.mediarecorder.width";
93 
94 // new fields, not yet frozen in the public Java API definitions
95 static const char *kRecorderAudioMime = "android.media.mediarecorder.audio.mime";
96 static const char *kRecorderVideoMime = "android.media.mediarecorder.video.mime";
97 static const char *kRecorderDurationMs = "android.media.mediarecorder.durationMs";
98 static const char *kRecorderPaused = "android.media.mediarecorder.pausedMs";
99 static const char *kRecorderNumPauses = "android.media.mediarecorder.NPauses";
100 
101 
102 // To collect the encoder usage for the battery app
addBatteryData(uint32_t params)103 static void addBatteryData(uint32_t params) {
104     sp<IBinder> binder =
105         defaultServiceManager()->getService(String16("media.player"));
106     sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
107     CHECK(service.get() != NULL);
108 
109     service->addBatteryData(params);
110 }
111 
112 
StagefrightRecorder(const String16 & opPackageName)113 StagefrightRecorder::StagefrightRecorder(const String16 &opPackageName)
114     : MediaRecorderBase(opPackageName),
115       mWriter(NULL),
116       mOutputFd(-1),
117       mAudioSource((audio_source_t)AUDIO_SOURCE_CNT), // initialize with invalid value
118       mPrivacySensitive(PRIVACY_SENSITIVE_DEFAULT),
119       mVideoSource(VIDEO_SOURCE_LIST_END),
120       mStarted(false),
121       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
122       mDeviceCallbackEnabled(false),
123       mSelectedMicDirection(MIC_DIRECTION_UNSPECIFIED),
124       mSelectedMicFieldDimension(MIC_FIELD_DIMENSION_NORMAL) {
125 
126     ALOGV("Constructor");
127 
128     mAnalyticsDirty = false;
129     reset();
130 }
131 
~StagefrightRecorder()132 StagefrightRecorder::~StagefrightRecorder() {
133     ALOGV("Destructor");
134     stop();
135 
136     if (mLooper != NULL) {
137         mLooper->stop();
138     }
139 
140     // log the current record, provided it has some information worth recording
141     // NB: this also reclaims & clears mMetricsItem.
142     flushAndResetMetrics(false);
143 }
144 
updateMetrics()145 void StagefrightRecorder::updateMetrics() {
146     ALOGV("updateMetrics");
147 
148     // we run as part of the media player service; what we really want to
149     // know is the app which requested the recording.
150     mMetricsItem->setUid(mClientUid);
151 
152     // populate the values from the raw fields.
153 
154     // TBD mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
155     // TBD mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
156     // TBD mVideoEncoder  = VIDEO_ENCODER_DEFAULT;
157     mMetricsItem->setInt32(kRecorderHeight, mVideoHeight);
158     mMetricsItem->setInt32(kRecorderWidth, mVideoWidth);
159     mMetricsItem->setInt32(kRecorderFrameRate, mFrameRate);
160     mMetricsItem->setInt32(kRecorderVideoBitrate, mVideoBitRate);
161     mMetricsItem->setInt32(kRecorderAudioSampleRate, mSampleRate);
162     mMetricsItem->setInt32(kRecorderAudioChannels, mAudioChannels);
163     mMetricsItem->setInt32(kRecorderAudioBitrate, mAudioBitRate);
164     // TBD mInterleaveDurationUs = 0;
165     mMetricsItem->setInt32(kRecorderVideoIframeInterval, mIFramesIntervalSec);
166     // TBD mAudioSourceNode = 0;
167     // TBD mUse64BitFileOffset = false;
168     if (mMovieTimeScale != -1)
169         mMetricsItem->setInt32(kRecorderMovieTimescale, mMovieTimeScale);
170     if (mAudioTimeScale != -1)
171         mMetricsItem->setInt32(kRecorderAudioTimescale, mAudioTimeScale);
172     if (mVideoTimeScale != -1)
173         mMetricsItem->setInt32(kRecorderVideoTimescale, mVideoTimeScale);
174     // TBD mCameraId        = 0;
175     // TBD mStartTimeOffsetMs = -1;
176     mMetricsItem->setInt32(kRecorderVideoProfile, mVideoEncoderProfile);
177     mMetricsItem->setInt32(kRecorderVideoLevel, mVideoEncoderLevel);
178     // TBD mMaxFileDurationUs = 0;
179     // TBD mMaxFileSizeBytes = 0;
180     // TBD mTrackEveryTimeDurationUs = 0;
181     mMetricsItem->setInt32(kRecorderCaptureFpsEnable, mCaptureFpsEnable);
182     mMetricsItem->setDouble(kRecorderCaptureFps, mCaptureFps);
183     // TBD mCameraSourceTimeLapse = NULL;
184     // TBD mMetaDataStoredInVideoBuffers = kMetadataBufferTypeInvalid;
185     // TBD mEncoderProfiles = MediaProfiles::getInstance();
186     mMetricsItem->setInt32(kRecorderRotation, mRotationDegrees);
187     // PII mLatitudex10000 = -3600000;
188     // PII mLongitudex10000 = -3600000;
189     // TBD mTotalBitRate = 0;
190 
191     // duration information (recorded, paused, # of pauses)
192     mMetricsItem->setInt64(kRecorderDurationMs, (mDurationRecordedUs+500)/1000 );
193     if (mNPauses != 0) {
194         mMetricsItem->setInt64(kRecorderPaused, (mDurationPausedUs+500)/1000 );
195         mMetricsItem->setInt32(kRecorderNumPauses, mNPauses);
196     }
197 }
198 
flushAndResetMetrics(bool reinitialize)199 void StagefrightRecorder::flushAndResetMetrics(bool reinitialize) {
200     ALOGV("flushAndResetMetrics");
201     // flush anything we have, maybe setup a new record
202     if (mAnalyticsDirty && mMetricsItem != NULL) {
203         updateMetrics();
204         if (mMetricsItem->count() > 0) {
205             mMetricsItem->selfrecord();
206         }
207         delete mMetricsItem;
208         mMetricsItem = NULL;
209     }
210     mAnalyticsDirty = false;
211     if (reinitialize) {
212         mMetricsItem = mediametrics::Item::create(kKeyRecorder);
213     }
214 }
215 
init()216 status_t StagefrightRecorder::init() {
217     ALOGV("init");
218 
219     mLooper = new ALooper;
220     mLooper->setName("recorder_looper");
221     mLooper->start();
222 
223     return OK;
224 }
225 
226 // The client side of mediaserver asks it to create a SurfaceMediaSource
227 // and return a interface reference. The client side will use that
228 // while encoding GL Frames
querySurfaceMediaSource() const229 sp<IGraphicBufferProducer> StagefrightRecorder::querySurfaceMediaSource() const {
230     ALOGV("Get SurfaceMediaSource");
231     return mGraphicBufferProducer;
232 }
233 
setAudioSource(audio_source_t as)234 status_t StagefrightRecorder::setAudioSource(audio_source_t as) {
235     ALOGV("setAudioSource: %d", as);
236 
237     if (as == AUDIO_SOURCE_DEFAULT) {
238         mAudioSource = AUDIO_SOURCE_MIC;
239     } else {
240         mAudioSource = as;
241     }
242     // Reset privacy sensitive in case this is the second time audio source is set
243     mPrivacySensitive = PRIVACY_SENSITIVE_DEFAULT;
244     return OK;
245 }
246 
setPrivacySensitive(bool privacySensitive)247 status_t StagefrightRecorder::setPrivacySensitive(bool privacySensitive) {
248     // privacy sensitive cannot be set before audio source is set
249     if (mAudioSource == AUDIO_SOURCE_CNT) {
250         return INVALID_OPERATION;
251     }
252     mPrivacySensitive = privacySensitive ? PRIVACY_SENSITIVE_ENABLED : PRIVACY_SENSITIVE_DISABLED;
253     return OK;
254 }
255 
isPrivacySensitive(bool * privacySensitive) const256 status_t StagefrightRecorder::isPrivacySensitive(bool *privacySensitive) const {
257     *privacySensitive = false;
258     if (mAudioSource == AUDIO_SOURCE_CNT) {
259         return INVALID_OPERATION;
260     }
261     if (mPrivacySensitive == PRIVACY_SENSITIVE_DEFAULT) {
262          *privacySensitive = mAudioSource == AUDIO_SOURCE_VOICE_COMMUNICATION
263                 || mAudioSource == AUDIO_SOURCE_CAMCORDER;
264     } else {
265         *privacySensitive = mPrivacySensitive == PRIVACY_SENSITIVE_ENABLED;
266     }
267     return OK;
268 }
269 
setVideoSource(video_source vs)270 status_t StagefrightRecorder::setVideoSource(video_source vs) {
271     ALOGV("setVideoSource: %d", vs);
272     if (vs < VIDEO_SOURCE_DEFAULT ||
273         vs >= VIDEO_SOURCE_LIST_END) {
274         ALOGE("Invalid video source: %d", vs);
275         return BAD_VALUE;
276     }
277 
278     if (vs == VIDEO_SOURCE_DEFAULT) {
279         mVideoSource = VIDEO_SOURCE_CAMERA;
280     } else {
281         mVideoSource = vs;
282     }
283 
284     return OK;
285 }
286 
setOutputFormat(output_format of)287 status_t StagefrightRecorder::setOutputFormat(output_format of) {
288     ALOGV("setOutputFormat: %d", of);
289     if (of < OUTPUT_FORMAT_DEFAULT ||
290         of >= OUTPUT_FORMAT_LIST_END) {
291         ALOGE("Invalid output format: %d", of);
292         return BAD_VALUE;
293     }
294 
295     if (of == OUTPUT_FORMAT_DEFAULT) {
296         mOutputFormat = OUTPUT_FORMAT_THREE_GPP;
297     } else {
298         mOutputFormat = of;
299     }
300 
301     return OK;
302 }
303 
setAudioEncoder(audio_encoder ae)304 status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
305     ALOGV("setAudioEncoder: %d", ae);
306     if (ae < AUDIO_ENCODER_DEFAULT ||
307         ae >= AUDIO_ENCODER_LIST_END) {
308         ALOGE("Invalid audio encoder: %d", ae);
309         return BAD_VALUE;
310     }
311 
312     if (ae == AUDIO_ENCODER_DEFAULT) {
313         mAudioEncoder = AUDIO_ENCODER_AMR_NB;
314     } else {
315         mAudioEncoder = ae;
316     }
317 
318     return OK;
319 }
320 
setVideoEncoder(video_encoder ve)321 status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
322     ALOGV("setVideoEncoder: %d", ve);
323     if (ve < VIDEO_ENCODER_DEFAULT ||
324         ve >= VIDEO_ENCODER_LIST_END) {
325         ALOGE("Invalid video encoder: %d", ve);
326         return BAD_VALUE;
327     }
328 
329     mVideoEncoder = ve;
330 
331     return OK;
332 }
333 
setVideoSize(int width,int height)334 status_t StagefrightRecorder::setVideoSize(int width, int height) {
335     ALOGV("setVideoSize: %dx%d", width, height);
336     if (width <= 0 || height <= 0) {
337         ALOGE("Invalid video size: %dx%d", width, height);
338         return BAD_VALUE;
339     }
340 
341     // Additional check on the dimension will be performed later
342     mVideoWidth = width;
343     mVideoHeight = height;
344 
345     return OK;
346 }
347 
setVideoFrameRate(int frames_per_second)348 status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
349     ALOGV("setVideoFrameRate: %d", frames_per_second);
350     if ((frames_per_second <= 0 && frames_per_second != -1) ||
351         frames_per_second > kMaxHighSpeedFps) {
352         ALOGE("Invalid video frame rate: %d", frames_per_second);
353         return BAD_VALUE;
354     }
355 
356     // Additional check on the frame rate will be performed later
357     mFrameRate = frames_per_second;
358 
359     return OK;
360 }
361 
setCamera(const sp<hardware::ICamera> & camera,const sp<ICameraRecordingProxy> & proxy)362 status_t StagefrightRecorder::setCamera(const sp<hardware::ICamera> &camera,
363                                         const sp<ICameraRecordingProxy> &proxy) {
364     ALOGV("setCamera");
365     if (camera == 0) {
366         ALOGE("camera is NULL");
367         return BAD_VALUE;
368     }
369     if (proxy == 0) {
370         ALOGE("camera proxy is NULL");
371         return BAD_VALUE;
372     }
373 
374     mCamera = camera;
375     mCameraProxy = proxy;
376     return OK;
377 }
378 
setPreviewSurface(const sp<IGraphicBufferProducer> & surface)379 status_t StagefrightRecorder::setPreviewSurface(const sp<IGraphicBufferProducer> &surface) {
380     ALOGV("setPreviewSurface: %p", surface.get());
381     mPreviewSurface = surface;
382 
383     return OK;
384 }
385 
setInputSurface(const sp<PersistentSurface> & surface)386 status_t StagefrightRecorder::setInputSurface(
387         const sp<PersistentSurface>& surface) {
388     mPersistentSurface = surface;
389 
390     return OK;
391 }
392 
setOutputFile(int fd)393 status_t StagefrightRecorder::setOutputFile(int fd) {
394     ALOGV("setOutputFile: %d", fd);
395 
396     if (fd < 0) {
397         ALOGE("Invalid file descriptor: %d", fd);
398         return -EBADF;
399     }
400 
401     // start with a clean, empty file
402     ftruncate(fd, 0);
403 
404     if (mOutputFd >= 0) {
405         ::close(mOutputFd);
406     }
407     mOutputFd = dup(fd);
408 
409     return OK;
410 }
411 
setNextOutputFile(int fd)412 status_t StagefrightRecorder::setNextOutputFile(int fd) {
413     Mutex::Autolock autolock(mLock);
414     // Only support MPEG4
415     if (mOutputFormat != OUTPUT_FORMAT_MPEG_4) {
416         ALOGE("Only MP4 file format supports setting next output file");
417         return INVALID_OPERATION;
418     }
419     ALOGV("setNextOutputFile: %d", fd);
420 
421     if (fd < 0) {
422         ALOGE("Invalid file descriptor: %d", fd);
423         return -EBADF;
424     }
425 
426     if (mWriter == nullptr) {
427         ALOGE("setNextOutputFile failed. Writer has been freed");
428         return INVALID_OPERATION;
429     }
430 
431     // start with a clean, empty file
432     ftruncate(fd, 0);
433 
434     return mWriter->setNextFd(fd);
435 }
436 
437 // Attempt to parse an float literal optionally surrounded by whitespace,
438 // returns true on success, false otherwise.
safe_strtod(const char * s,double * val)439 static bool safe_strtod(const char *s, double *val) {
440     char *end;
441 
442     // It is lame, but according to man page, we have to set errno to 0
443     // before calling strtod().
444     errno = 0;
445     *val = strtod(s, &end);
446 
447     if (end == s || errno == ERANGE) {
448         return false;
449     }
450 
451     // Skip trailing whitespace
452     while (isspace(*end)) {
453         ++end;
454     }
455 
456     // For a successful return, the string must contain nothing but a valid
457     // float literal optionally surrounded by whitespace.
458 
459     return *end == '\0';
460 }
461 
462 // Attempt to parse an int64 literal optionally surrounded by whitespace,
463 // returns true on success, false otherwise.
safe_strtoi64(const char * s,int64_t * val)464 static bool safe_strtoi64(const char *s, int64_t *val) {
465     char *end;
466 
467     // It is lame, but according to man page, we have to set errno to 0
468     // before calling strtoll().
469     errno = 0;
470     *val = strtoll(s, &end, 10);
471 
472     if (end == s || errno == ERANGE) {
473         return false;
474     }
475 
476     // Skip trailing whitespace
477     while (isspace(*end)) {
478         ++end;
479     }
480 
481     // For a successful return, the string must contain nothing but a valid
482     // int64 literal optionally surrounded by whitespace.
483 
484     return *end == '\0';
485 }
486 
487 // Return true if the value is in [0, 0x007FFFFFFF]
safe_strtoi32(const char * s,int32_t * val)488 static bool safe_strtoi32(const char *s, int32_t *val) {
489     int64_t temp;
490     if (safe_strtoi64(s, &temp)) {
491         if (temp >= 0 && temp <= 0x007FFFFFFF) {
492             *val = static_cast<int32_t>(temp);
493             return true;
494         }
495     }
496     return false;
497 }
498 
499 // Trim both leading and trailing whitespace from the given string.
TrimString(String8 * s)500 static void TrimString(String8 *s) {
501     size_t num_bytes = s->bytes();
502     const char *data = s->string();
503 
504     size_t leading_space = 0;
505     while (leading_space < num_bytes && isspace(data[leading_space])) {
506         ++leading_space;
507     }
508 
509     size_t i = num_bytes;
510     while (i > leading_space && isspace(data[i - 1])) {
511         --i;
512     }
513 
514     s->setTo(String8(&data[leading_space], i - leading_space));
515 }
516 
setParamAudioSamplingRate(int32_t sampleRate)517 status_t StagefrightRecorder::setParamAudioSamplingRate(int32_t sampleRate) {
518     ALOGV("setParamAudioSamplingRate: %d", sampleRate);
519     if (sampleRate <= 0) {
520         ALOGE("Invalid audio sampling rate: %d", sampleRate);
521         return BAD_VALUE;
522     }
523 
524     // Additional check on the sample rate will be performed later.
525     mSampleRate = sampleRate;
526 
527     return OK;
528 }
529 
setParamAudioNumberOfChannels(int32_t channels)530 status_t StagefrightRecorder::setParamAudioNumberOfChannels(int32_t channels) {
531     ALOGV("setParamAudioNumberOfChannels: %d", channels);
532     if (channels <= 0 || channels >= 3) {
533         ALOGE("Invalid number of audio channels: %d", channels);
534         return BAD_VALUE;
535     }
536 
537     // Additional check on the number of channels will be performed later.
538     mAudioChannels = channels;
539 
540     return OK;
541 }
542 
setParamAudioEncodingBitRate(int32_t bitRate)543 status_t StagefrightRecorder::setParamAudioEncodingBitRate(int32_t bitRate) {
544     ALOGV("setParamAudioEncodingBitRate: %d", bitRate);
545     if (bitRate <= 0) {
546         ALOGE("Invalid audio encoding bit rate: %d", bitRate);
547         return BAD_VALUE;
548     }
549 
550     // The target bit rate may not be exactly the same as the requested.
551     // It depends on many factors, such as rate control, and the bit rate
552     // range that a specific encoder supports. The mismatch between the
553     // the target and requested bit rate will NOT be treated as an error.
554     mAudioBitRate = bitRate;
555     return OK;
556 }
557 
setParamVideoEncodingBitRate(int32_t bitRate)558 status_t StagefrightRecorder::setParamVideoEncodingBitRate(int32_t bitRate) {
559     ALOGV("setParamVideoEncodingBitRate: %d", bitRate);
560     if (bitRate <= 0) {
561         ALOGE("Invalid video encoding bit rate: %d", bitRate);
562         return BAD_VALUE;
563     }
564 
565     // The target bit rate may not be exactly the same as the requested.
566     // It depends on many factors, such as rate control, and the bit rate
567     // range that a specific encoder supports. The mismatch between the
568     // the target and requested bit rate will NOT be treated as an error.
569     mVideoBitRate = bitRate;
570     return OK;
571 }
572 
573 // Always rotate clockwise, and only support 0, 90, 180 and 270 for now.
setParamVideoRotation(int32_t degrees)574 status_t StagefrightRecorder::setParamVideoRotation(int32_t degrees) {
575     ALOGV("setParamVideoRotation: %d", degrees);
576     if (degrees < 0 || degrees % 90 != 0) {
577         ALOGE("Unsupported video rotation angle: %d", degrees);
578         return BAD_VALUE;
579     }
580     mRotationDegrees = degrees % 360;
581     return OK;
582 }
583 
setParamMaxFileDurationUs(int64_t timeUs)584 status_t StagefrightRecorder::setParamMaxFileDurationUs(int64_t timeUs) {
585     ALOGV("setParamMaxFileDurationUs: %lld us", (long long)timeUs);
586 
587     // This is meant for backward compatibility for MediaRecorder.java
588     if (timeUs <= 0) {
589         ALOGW("Max file duration is not positive: %lld us. Disabling duration limit.",
590                 (long long)timeUs);
591         timeUs = 0; // Disable the duration limit for zero or negative values.
592     } else if (timeUs <= 100000LL) {  // XXX: 100 milli-seconds
593         ALOGE("Max file duration is too short: %lld us", (long long)timeUs);
594         return BAD_VALUE;
595     }
596 
597     if (timeUs <= 15 * 1000000LL) {
598         ALOGW("Target duration (%lld us) too short to be respected", (long long)timeUs);
599     }
600     mMaxFileDurationUs = timeUs;
601     return OK;
602 }
603 
setParamMaxFileSizeBytes(int64_t bytes)604 status_t StagefrightRecorder::setParamMaxFileSizeBytes(int64_t bytes) {
605     ALOGV("setParamMaxFileSizeBytes: %lld bytes", (long long)bytes);
606 
607     // This is meant for backward compatibility for MediaRecorder.java
608     if (bytes <= 0) {
609         ALOGW("Max file size is not positive: %lld bytes. "
610              "Disabling file size limit.", (long long)bytes);
611         bytes = 0; // Disable the file size limit for zero or negative values.
612     } else if (bytes <= 1024) {  // XXX: 1 kB
613         ALOGE("Max file size is too small: %lld bytes", (long long)bytes);
614         return BAD_VALUE;
615     }
616 
617     if (bytes <= 100 * 1024) {
618         ALOGW("Target file size (%lld bytes) is too small to be respected", (long long)bytes);
619     }
620 
621     mMaxFileSizeBytes = bytes;
622     return OK;
623 }
624 
setParamInterleaveDuration(int32_t durationUs)625 status_t StagefrightRecorder::setParamInterleaveDuration(int32_t durationUs) {
626     ALOGV("setParamInterleaveDuration: %d", durationUs);
627     if (durationUs <= 500000) {           //  500 ms
628         // If interleave duration is too small, it is very inefficient to do
629         // interleaving since the metadata overhead will count for a significant
630         // portion of the saved contents
631         ALOGE("Audio/video interleave duration is too small: %d us", durationUs);
632         return BAD_VALUE;
633     } else if (durationUs >= 10000000) {  // 10 seconds
634         // If interleaving duration is too large, it can cause the recording
635         // session to use too much memory since we have to save the output
636         // data before we write them out
637         ALOGE("Audio/video interleave duration is too large: %d us", durationUs);
638         return BAD_VALUE;
639     }
640     mInterleaveDurationUs = durationUs;
641     return OK;
642 }
643 
644 // If seconds <  0, only the first frame is I frame, and rest are all P frames
645 // If seconds == 0, all frames are encoded as I frames. No P frames
646 // If seconds >  0, it is the time spacing (seconds) between 2 neighboring I frames
setParamVideoIFramesInterval(int32_t seconds)647 status_t StagefrightRecorder::setParamVideoIFramesInterval(int32_t seconds) {
648     ALOGV("setParamVideoIFramesInterval: %d seconds", seconds);
649     mIFramesIntervalSec = seconds;
650     return OK;
651 }
652 
setParam64BitFileOffset(bool use64Bit)653 status_t StagefrightRecorder::setParam64BitFileOffset(bool use64Bit) {
654     ALOGV("setParam64BitFileOffset: %s",
655         use64Bit? "use 64 bit file offset": "use 32 bit file offset");
656     mUse64BitFileOffset = use64Bit;
657     return OK;
658 }
659 
setParamVideoCameraId(int32_t cameraId)660 status_t StagefrightRecorder::setParamVideoCameraId(int32_t cameraId) {
661     ALOGV("setParamVideoCameraId: %d", cameraId);
662     if (cameraId < 0) {
663         return BAD_VALUE;
664     }
665     mCameraId = cameraId;
666     return OK;
667 }
668 
setParamTrackTimeStatus(int64_t timeDurationUs)669 status_t StagefrightRecorder::setParamTrackTimeStatus(int64_t timeDurationUs) {
670     ALOGV("setParamTrackTimeStatus: %lld", (long long)timeDurationUs);
671     if (timeDurationUs < 20000) {  // Infeasible if shorter than 20 ms?
672         ALOGE("Tracking time duration too short: %lld us", (long long)timeDurationUs);
673         return BAD_VALUE;
674     }
675     mTrackEveryTimeDurationUs = timeDurationUs;
676     return OK;
677 }
678 
setParamVideoEncoderProfile(int32_t profile)679 status_t StagefrightRecorder::setParamVideoEncoderProfile(int32_t profile) {
680     ALOGV("setParamVideoEncoderProfile: %d", profile);
681 
682     // Additional check will be done later when we load the encoder.
683     // For now, we are accepting values defined in OpenMAX IL.
684     mVideoEncoderProfile = profile;
685     return OK;
686 }
687 
setParamVideoEncoderLevel(int32_t level)688 status_t StagefrightRecorder::setParamVideoEncoderLevel(int32_t level) {
689     ALOGV("setParamVideoEncoderLevel: %d", level);
690 
691     // Additional check will be done later when we load the encoder.
692     // For now, we are accepting values defined in OpenMAX IL.
693     mVideoEncoderLevel = level;
694     return OK;
695 }
696 
setParamMovieTimeScale(int32_t timeScale)697 status_t StagefrightRecorder::setParamMovieTimeScale(int32_t timeScale) {
698     ALOGV("setParamMovieTimeScale: %d", timeScale);
699 
700     // The range is set to be the same as the audio's time scale range
701     // since audio's time scale has a wider range.
702     if (timeScale < 600 || timeScale > 96000) {
703         ALOGE("Time scale (%d) for movie is out of range [600, 96000]", timeScale);
704         return BAD_VALUE;
705     }
706     mMovieTimeScale = timeScale;
707     return OK;
708 }
709 
setParamVideoTimeScale(int32_t timeScale)710 status_t StagefrightRecorder::setParamVideoTimeScale(int32_t timeScale) {
711     ALOGV("setParamVideoTimeScale: %d", timeScale);
712 
713     // 60000 is chosen to make sure that each video frame from a 60-fps
714     // video has 1000 ticks.
715     if (timeScale < 600 || timeScale > 60000) {
716         ALOGE("Time scale (%d) for video is out of range [600, 60000]", timeScale);
717         return BAD_VALUE;
718     }
719     mVideoTimeScale = timeScale;
720     return OK;
721 }
722 
setParamAudioTimeScale(int32_t timeScale)723 status_t StagefrightRecorder::setParamAudioTimeScale(int32_t timeScale) {
724     ALOGV("setParamAudioTimeScale: %d", timeScale);
725 
726     // 96000 Hz is the highest sampling rate support in AAC.
727     if (timeScale < 600 || timeScale > 96000) {
728         ALOGE("Time scale (%d) for audio is out of range [600, 96000]", timeScale);
729         return BAD_VALUE;
730     }
731     mAudioTimeScale = timeScale;
732     return OK;
733 }
734 
setParamCaptureFpsEnable(int32_t captureFpsEnable)735 status_t StagefrightRecorder::setParamCaptureFpsEnable(int32_t captureFpsEnable) {
736     ALOGV("setParamCaptureFpsEnable: %d", captureFpsEnable);
737 
738     if(captureFpsEnable == 0) {
739         mCaptureFpsEnable = false;
740     } else if (captureFpsEnable == 1) {
741         mCaptureFpsEnable = true;
742     } else {
743         return BAD_VALUE;
744     }
745     return OK;
746 }
747 
setParamCaptureFps(double fps)748 status_t StagefrightRecorder::setParamCaptureFps(double fps) {
749     ALOGV("setParamCaptureFps: %.2f", fps);
750 
751     if (!(fps >= 1.0 / 86400)) {
752         ALOGE("FPS is too small");
753         return BAD_VALUE;
754     }
755     mCaptureFps = fps;
756     return OK;
757 }
758 
setParamGeoDataLongitude(int64_t longitudex10000)759 status_t StagefrightRecorder::setParamGeoDataLongitude(
760     int64_t longitudex10000) {
761 
762     if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
763         return BAD_VALUE;
764     }
765     mLongitudex10000 = longitudex10000;
766     return OK;
767 }
768 
setParamGeoDataLatitude(int64_t latitudex10000)769 status_t StagefrightRecorder::setParamGeoDataLatitude(
770     int64_t latitudex10000) {
771 
772     if (latitudex10000 > 900000 || latitudex10000 < -900000) {
773         return BAD_VALUE;
774     }
775     mLatitudex10000 = latitudex10000;
776     return OK;
777 }
778 
setParameter(const String8 & key,const String8 & value)779 status_t StagefrightRecorder::setParameter(
780         const String8 &key, const String8 &value) {
781     ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
782     if (key == "max-duration") {
783         int64_t max_duration_ms;
784         if (safe_strtoi64(value.string(), &max_duration_ms)) {
785             return setParamMaxFileDurationUs(1000LL * max_duration_ms);
786         }
787     } else if (key == "max-filesize") {
788         int64_t max_filesize_bytes;
789         if (safe_strtoi64(value.string(), &max_filesize_bytes)) {
790             return setParamMaxFileSizeBytes(max_filesize_bytes);
791         }
792     } else if (key == "interleave-duration-us") {
793         int32_t durationUs;
794         if (safe_strtoi32(value.string(), &durationUs)) {
795             return setParamInterleaveDuration(durationUs);
796         }
797     } else if (key == "param-movie-time-scale") {
798         int32_t timeScale;
799         if (safe_strtoi32(value.string(), &timeScale)) {
800             return setParamMovieTimeScale(timeScale);
801         }
802     } else if (key == "param-use-64bit-offset") {
803         int32_t use64BitOffset;
804         if (safe_strtoi32(value.string(), &use64BitOffset)) {
805             return setParam64BitFileOffset(use64BitOffset != 0);
806         }
807     } else if (key == "param-geotag-longitude") {
808         int64_t longitudex10000;
809         if (safe_strtoi64(value.string(), &longitudex10000)) {
810             return setParamGeoDataLongitude(longitudex10000);
811         }
812     } else if (key == "param-geotag-latitude") {
813         int64_t latitudex10000;
814         if (safe_strtoi64(value.string(), &latitudex10000)) {
815             return setParamGeoDataLatitude(latitudex10000);
816         }
817     } else if (key == "param-track-time-status") {
818         int64_t timeDurationUs;
819         if (safe_strtoi64(value.string(), &timeDurationUs)) {
820             return setParamTrackTimeStatus(timeDurationUs);
821         }
822     } else if (key == "audio-param-sampling-rate") {
823         int32_t sampling_rate;
824         if (safe_strtoi32(value.string(), &sampling_rate)) {
825             return setParamAudioSamplingRate(sampling_rate);
826         }
827     } else if (key == "audio-param-number-of-channels") {
828         int32_t number_of_channels;
829         if (safe_strtoi32(value.string(), &number_of_channels)) {
830             return setParamAudioNumberOfChannels(number_of_channels);
831         }
832     } else if (key == "audio-param-encoding-bitrate") {
833         int32_t audio_bitrate;
834         if (safe_strtoi32(value.string(), &audio_bitrate)) {
835             return setParamAudioEncodingBitRate(audio_bitrate);
836         }
837     } else if (key == "audio-param-time-scale") {
838         int32_t timeScale;
839         if (safe_strtoi32(value.string(), &timeScale)) {
840             return setParamAudioTimeScale(timeScale);
841         }
842     } else if (key == "video-param-encoding-bitrate") {
843         int32_t video_bitrate;
844         if (safe_strtoi32(value.string(), &video_bitrate)) {
845             return setParamVideoEncodingBitRate(video_bitrate);
846         }
847     } else if (key == "video-param-rotation-angle-degrees") {
848         int32_t degrees;
849         if (safe_strtoi32(value.string(), &degrees)) {
850             return setParamVideoRotation(degrees);
851         }
852     } else if (key == "video-param-i-frames-interval") {
853         int32_t seconds;
854         if (safe_strtoi32(value.string(), &seconds)) {
855             return setParamVideoIFramesInterval(seconds);
856         }
857     } else if (key == "video-param-encoder-profile") {
858         int32_t profile;
859         if (safe_strtoi32(value.string(), &profile)) {
860             return setParamVideoEncoderProfile(profile);
861         }
862     } else if (key == "video-param-encoder-level") {
863         int32_t level;
864         if (safe_strtoi32(value.string(), &level)) {
865             return setParamVideoEncoderLevel(level);
866         }
867     } else if (key == "video-param-camera-id") {
868         int32_t cameraId;
869         if (safe_strtoi32(value.string(), &cameraId)) {
870             return setParamVideoCameraId(cameraId);
871         }
872     } else if (key == "video-param-time-scale") {
873         int32_t timeScale;
874         if (safe_strtoi32(value.string(), &timeScale)) {
875             return setParamVideoTimeScale(timeScale);
876         }
877     } else if (key == "time-lapse-enable") {
878         int32_t captureFpsEnable;
879         if (safe_strtoi32(value.string(), &captureFpsEnable)) {
880             return setParamCaptureFpsEnable(captureFpsEnable);
881         }
882     } else if (key == "time-lapse-fps") {
883         double fps;
884         if (safe_strtod(value.string(), &fps)) {
885             return setParamCaptureFps(fps);
886         }
887     } else {
888         ALOGE("setParameter: failed to find key %s", key.string());
889     }
890     return BAD_VALUE;
891 }
892 
setParameters(const String8 & params)893 status_t StagefrightRecorder::setParameters(const String8 &params) {
894     ALOGV("setParameters: %s", params.string());
895     const char *cparams = params.string();
896     const char *key_start = cparams;
897     for (;;) {
898         const char *equal_pos = strchr(key_start, '=');
899         if (equal_pos == NULL) {
900             ALOGE("Parameters %s miss a value", cparams);
901             return BAD_VALUE;
902         }
903         String8 key(key_start, equal_pos - key_start);
904         TrimString(&key);
905         if (key.length() == 0) {
906             ALOGE("Parameters %s contains an empty key", cparams);
907             return BAD_VALUE;
908         }
909         const char *value_start = equal_pos + 1;
910         const char *semicolon_pos = strchr(value_start, ';');
911         String8 value;
912         if (semicolon_pos == NULL) {
913             value.setTo(value_start);
914         } else {
915             value.setTo(value_start, semicolon_pos - value_start);
916         }
917         if (setParameter(key, value) != OK) {
918             return BAD_VALUE;
919         }
920         if (semicolon_pos == NULL) {
921             break;  // Reaches the end
922         }
923         key_start = semicolon_pos + 1;
924     }
925     return OK;
926 }
927 
setListener(const sp<IMediaRecorderClient> & listener)928 status_t StagefrightRecorder::setListener(const sp<IMediaRecorderClient> &listener) {
929     mListener = listener;
930 
931     return OK;
932 }
933 
setClientName(const String16 & clientName)934 status_t StagefrightRecorder::setClientName(const String16& clientName) {
935     mClientName = clientName;
936 
937     return OK;
938 }
939 
prepareInternal()940 status_t StagefrightRecorder::prepareInternal() {
941     ALOGV("prepare");
942     if (mOutputFd < 0) {
943         ALOGE("Output file descriptor is invalid");
944         return INVALID_OPERATION;
945     }
946 
947     // Get UID and PID here for permission checking
948     mClientUid = IPCThreadState::self()->getCallingUid();
949     mClientPid = IPCThreadState::self()->getCallingPid();
950 
951     status_t status = OK;
952 
953     switch (mOutputFormat) {
954         case OUTPUT_FORMAT_DEFAULT:
955         case OUTPUT_FORMAT_THREE_GPP:
956         case OUTPUT_FORMAT_MPEG_4:
957         case OUTPUT_FORMAT_WEBM:
958             status = setupMPEG4orWEBMRecording();
959             break;
960 
961         case OUTPUT_FORMAT_AMR_NB:
962         case OUTPUT_FORMAT_AMR_WB:
963             status = setupAMRRecording();
964             break;
965 
966         case OUTPUT_FORMAT_AAC_ADIF:
967         case OUTPUT_FORMAT_AAC_ADTS:
968             status = setupAACRecording();
969             break;
970 
971         case OUTPUT_FORMAT_RTP_AVP:
972             status = setupRTPRecording();
973             break;
974 
975         case OUTPUT_FORMAT_MPEG2TS:
976             status = setupMPEG2TSRecording();
977             break;
978 
979         case OUTPUT_FORMAT_OGG:
980             status = setupOggRecording();
981             break;
982 
983         default:
984             ALOGE("Unsupported output file format: %d", mOutputFormat);
985             status = UNKNOWN_ERROR;
986             break;
987     }
988 
989     ALOGV("Recording frameRate: %d captureFps: %f",
990             mFrameRate, mCaptureFps);
991 
992     return status;
993 }
994 
prepare()995 status_t StagefrightRecorder::prepare() {
996     ALOGV("prepare");
997     Mutex::Autolock autolock(mLock);
998     if (mVideoSource == VIDEO_SOURCE_SURFACE) {
999         return prepareInternal();
1000     }
1001     return OK;
1002 }
1003 
start()1004 status_t StagefrightRecorder::start() {
1005     ALOGV("start");
1006     Mutex::Autolock autolock(mLock);
1007     if (mOutputFd < 0) {
1008         ALOGE("Output file descriptor is invalid");
1009         return INVALID_OPERATION;
1010     }
1011 
1012     status_t status = OK;
1013 
1014     if (mVideoSource != VIDEO_SOURCE_SURFACE) {
1015         status = prepareInternal();
1016         if (status != OK) {
1017             return status;
1018         }
1019     }
1020 
1021     if (mWriter == NULL) {
1022         ALOGE("File writer is not avaialble");
1023         return UNKNOWN_ERROR;
1024     }
1025 
1026     switch (mOutputFormat) {
1027         case OUTPUT_FORMAT_DEFAULT:
1028         case OUTPUT_FORMAT_THREE_GPP:
1029         case OUTPUT_FORMAT_MPEG_4:
1030         case OUTPUT_FORMAT_WEBM:
1031         {
1032             bool isMPEG4 = true;
1033             if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1034                 isMPEG4 = false;
1035             }
1036             sp<MetaData> meta = new MetaData;
1037             setupMPEG4orWEBMMetaData(&meta);
1038             status = mWriter->start(meta.get());
1039             break;
1040         }
1041 
1042         case OUTPUT_FORMAT_AMR_NB:
1043         case OUTPUT_FORMAT_AMR_WB:
1044         case OUTPUT_FORMAT_AAC_ADIF:
1045         case OUTPUT_FORMAT_AAC_ADTS:
1046         case OUTPUT_FORMAT_RTP_AVP:
1047         case OUTPUT_FORMAT_MPEG2TS:
1048         case OUTPUT_FORMAT_OGG:
1049         {
1050             sp<MetaData> meta = new MetaData;
1051             int64_t startTimeUs = systemTime() / 1000;
1052             meta->setInt64(kKeyTime, startTimeUs);
1053             status = mWriter->start(meta.get());
1054             break;
1055         }
1056 
1057         default:
1058         {
1059             ALOGE("Unsupported output file format: %d", mOutputFormat);
1060             status = UNKNOWN_ERROR;
1061             break;
1062         }
1063     }
1064 
1065     if (status != OK) {
1066         mWriter.clear();
1067         mWriter = NULL;
1068     }
1069 
1070     if ((status == OK) && (!mStarted)) {
1071         mAnalyticsDirty = true;
1072         mStarted = true;
1073 
1074         mStartedRecordingUs = systemTime() / 1000;
1075 
1076         uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted;
1077         if (mAudioSource != AUDIO_SOURCE_CNT) {
1078             params |= IMediaPlayerService::kBatteryDataTrackAudio;
1079         }
1080         if (mVideoSource != VIDEO_SOURCE_LIST_END) {
1081             params |= IMediaPlayerService::kBatteryDataTrackVideo;
1082         }
1083 
1084         addBatteryData(params);
1085     }
1086 
1087     return status;
1088 }
1089 
createAudioSource()1090 sp<MediaCodecSource> StagefrightRecorder::createAudioSource() {
1091     int32_t sourceSampleRate = mSampleRate;
1092 
1093     if (mCaptureFpsEnable && mCaptureFps >= mFrameRate) {
1094         // Upscale the sample rate for slow motion recording.
1095         // Fail audio source creation if source sample rate is too high, as it could
1096         // cause out-of-memory due to large input buffer size. And audio recording
1097         // probably doesn't make sense in the scenario, since the slow-down factor
1098         // is probably huge (eg. mSampleRate=48K, mCaptureFps=240, mFrameRate=1).
1099         const static int32_t SAMPLE_RATE_HZ_MAX = 192000;
1100         sourceSampleRate =
1101                 (mSampleRate * mCaptureFps + mFrameRate / 2) / mFrameRate;
1102         if (sourceSampleRate < mSampleRate || sourceSampleRate > SAMPLE_RATE_HZ_MAX) {
1103             ALOGE("source sample rate out of range! "
1104                     "(mSampleRate %d, mCaptureFps %.2f, mFrameRate %d",
1105                     mSampleRate, mCaptureFps, mFrameRate);
1106             return NULL;
1107         }
1108     }
1109 
1110     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
1111     attr.source = mAudioSource;
1112     // attr.flags AUDIO_FLAG_CAPTURE_PRIVATE is cleared by default
1113     if (mPrivacySensitive == PRIVACY_SENSITIVE_DEFAULT) {
1114         if (attr.source == AUDIO_SOURCE_VOICE_COMMUNICATION
1115                 || attr.source == AUDIO_SOURCE_CAMCORDER) {
1116             attr.flags |= AUDIO_FLAG_CAPTURE_PRIVATE;
1117             mPrivacySensitive = PRIVACY_SENSITIVE_ENABLED;
1118         } else {
1119             mPrivacySensitive = PRIVACY_SENSITIVE_DISABLED;
1120         }
1121     } else {
1122         if (mAudioSource == AUDIO_SOURCE_REMOTE_SUBMIX
1123                 || mAudioSource == AUDIO_SOURCE_FM_TUNER
1124                 || mAudioSource == AUDIO_SOURCE_VOICE_DOWNLINK
1125                 || mAudioSource == AUDIO_SOURCE_VOICE_UPLINK
1126                 || mAudioSource == AUDIO_SOURCE_VOICE_CALL
1127                 || mAudioSource == AUDIO_SOURCE_ECHO_REFERENCE) {
1128             ALOGE("Cannot request private capture with source: %d", mAudioSource);
1129             return NULL;
1130         }
1131         if (mPrivacySensitive == PRIVACY_SENSITIVE_ENABLED) {
1132             attr.flags |= AUDIO_FLAG_CAPTURE_PRIVATE;
1133         }
1134     }
1135 
1136     sp<AudioSource> audioSource =
1137         new AudioSource(
1138                 &attr,
1139                 mOpPackageName,
1140                 sourceSampleRate,
1141                 mAudioChannels,
1142                 mSampleRate,
1143                 mClientUid,
1144                 mClientPid,
1145                 mSelectedDeviceId,
1146                 mSelectedMicDirection,
1147                 mSelectedMicFieldDimension);
1148 
1149     status_t err = audioSource->initCheck();
1150 
1151     if (err != OK) {
1152         ALOGE("audio source is not initialized");
1153         return NULL;
1154     }
1155 
1156     sp<AMessage> format = new AMessage;
1157     switch (mAudioEncoder) {
1158         case AUDIO_ENCODER_AMR_NB:
1159         case AUDIO_ENCODER_DEFAULT:
1160             format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_NB);
1161             break;
1162         case AUDIO_ENCODER_AMR_WB:
1163             format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_WB);
1164             break;
1165         case AUDIO_ENCODER_AAC:
1166             format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
1167             format->setInt32("aac-profile", OMX_AUDIO_AACObjectLC);
1168             break;
1169         case AUDIO_ENCODER_HE_AAC:
1170             format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
1171             format->setInt32("aac-profile", OMX_AUDIO_AACObjectHE);
1172             break;
1173         case AUDIO_ENCODER_AAC_ELD:
1174             format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
1175             format->setInt32("aac-profile", OMX_AUDIO_AACObjectELD);
1176             break;
1177         case AUDIO_ENCODER_OPUS:
1178             format->setString("mime", MEDIA_MIMETYPE_AUDIO_OPUS);
1179             break;
1180 
1181         default:
1182             ALOGE("Unknown audio encoder: %d", mAudioEncoder);
1183             return NULL;
1184     }
1185 
1186     // log audio mime type for media metrics
1187     if (mMetricsItem != NULL) {
1188         AString audiomime;
1189         if (format->findString("mime", &audiomime)) {
1190             mMetricsItem->setCString(kRecorderAudioMime, audiomime.c_str());
1191         }
1192     }
1193 
1194     int32_t maxInputSize;
1195     CHECK(audioSource->getFormat()->findInt32(
1196                 kKeyMaxInputSize, &maxInputSize));
1197 
1198     format->setInt32("max-input-size", maxInputSize);
1199     format->setInt32("channel-count", mAudioChannels);
1200     format->setInt32("sample-rate", mSampleRate);
1201     format->setInt32("bitrate", mAudioBitRate);
1202     if (mAudioTimeScale > 0) {
1203         format->setInt32("time-scale", mAudioTimeScale);
1204     }
1205     format->setInt32("priority", 0 /* realtime */);
1206 
1207     sp<MediaCodecSource> audioEncoder =
1208             MediaCodecSource::Create(mLooper, format, audioSource);
1209     sp<AudioSystem::AudioDeviceCallback> callback = mAudioDeviceCallback.promote();
1210     if (mDeviceCallbackEnabled && callback != 0) {
1211         audioSource->addAudioDeviceCallback(callback);
1212     }
1213     mAudioSourceNode = audioSource;
1214 
1215     if (audioEncoder == NULL) {
1216         ALOGE("Failed to create audio encoder");
1217     }
1218 
1219     return audioEncoder;
1220 }
1221 
setupAACRecording()1222 status_t StagefrightRecorder::setupAACRecording() {
1223     // FIXME:
1224     // Add support for OUTPUT_FORMAT_AAC_ADIF
1225     CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_AAC_ADTS);
1226 
1227     CHECK(mAudioEncoder == AUDIO_ENCODER_AAC ||
1228           mAudioEncoder == AUDIO_ENCODER_HE_AAC ||
1229           mAudioEncoder == AUDIO_ENCODER_AAC_ELD);
1230     CHECK(mAudioSource != AUDIO_SOURCE_CNT);
1231 
1232     mWriter = new AACWriter(mOutputFd);
1233     return setupRawAudioRecording();
1234 }
1235 
setupOggRecording()1236 status_t StagefrightRecorder::setupOggRecording() {
1237     CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_OGG);
1238 
1239     mWriter = new OggWriter(mOutputFd);
1240     return setupRawAudioRecording();
1241 }
1242 
setupAMRRecording()1243 status_t StagefrightRecorder::setupAMRRecording() {
1244     CHECK(mOutputFormat == OUTPUT_FORMAT_AMR_NB ||
1245           mOutputFormat == OUTPUT_FORMAT_AMR_WB);
1246 
1247     if (mOutputFormat == OUTPUT_FORMAT_AMR_NB) {
1248         if (mAudioEncoder != AUDIO_ENCODER_DEFAULT &&
1249             mAudioEncoder != AUDIO_ENCODER_AMR_NB) {
1250             ALOGE("Invalid encoder %d used for AMRNB recording",
1251                     mAudioEncoder);
1252             return BAD_VALUE;
1253         }
1254     } else {  // mOutputFormat must be OUTPUT_FORMAT_AMR_WB
1255         if (mAudioEncoder != AUDIO_ENCODER_AMR_WB) {
1256             ALOGE("Invlaid encoder %d used for AMRWB recording",
1257                     mAudioEncoder);
1258             return BAD_VALUE;
1259         }
1260     }
1261 
1262     mWriter = new AMRWriter(mOutputFd);
1263     return setupRawAudioRecording();
1264 }
1265 
setupRawAudioRecording()1266 status_t StagefrightRecorder::setupRawAudioRecording() {
1267     if (mAudioSource >= AUDIO_SOURCE_CNT && mAudioSource != AUDIO_SOURCE_FM_TUNER) {
1268         ALOGE("Invalid audio source: %d", mAudioSource);
1269         return BAD_VALUE;
1270     }
1271 
1272     status_t status = BAD_VALUE;
1273     if (OK != (status = checkAudioEncoderCapabilities())) {
1274         return status;
1275     }
1276 
1277     sp<MediaCodecSource> audioEncoder = createAudioSource();
1278     if (audioEncoder == NULL) {
1279         return UNKNOWN_ERROR;
1280     }
1281 
1282     CHECK(mWriter != 0);
1283     mWriter->addSource(audioEncoder);
1284     mAudioEncoderSource = audioEncoder;
1285 
1286     if (mMaxFileDurationUs != 0) {
1287         mWriter->setMaxFileDuration(mMaxFileDurationUs);
1288     }
1289     if (mMaxFileSizeBytes != 0) {
1290         mWriter->setMaxFileSize(mMaxFileSizeBytes);
1291     }
1292     mWriter->setListener(mListener);
1293 
1294     return OK;
1295 }
1296 
setupRTPRecording()1297 status_t StagefrightRecorder::setupRTPRecording() {
1298     CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_RTP_AVP);
1299 
1300     if ((mAudioSource != AUDIO_SOURCE_CNT
1301                 && mVideoSource != VIDEO_SOURCE_LIST_END)
1302             || (mAudioSource == AUDIO_SOURCE_CNT
1303                 && mVideoSource == VIDEO_SOURCE_LIST_END)) {
1304         // Must have exactly one source.
1305         return BAD_VALUE;
1306     }
1307 
1308     if (mOutputFd < 0) {
1309         return BAD_VALUE;
1310     }
1311 
1312     sp<MediaCodecSource> source;
1313 
1314     if (mAudioSource != AUDIO_SOURCE_CNT) {
1315         source = createAudioSource();
1316         mAudioEncoderSource = source;
1317     } else {
1318         setDefaultVideoEncoderIfNecessary();
1319 
1320         sp<MediaSource> mediaSource;
1321         status_t err = setupMediaSource(&mediaSource);
1322         if (err != OK) {
1323             return err;
1324         }
1325 
1326         err = setupVideoEncoder(mediaSource, &source);
1327         if (err != OK) {
1328             return err;
1329         }
1330         mVideoEncoderSource = source;
1331     }
1332 
1333     mWriter = new ARTPWriter(mOutputFd);
1334     mWriter->addSource(source);
1335     mWriter->setListener(mListener);
1336 
1337     return OK;
1338 }
1339 
setupMPEG2TSRecording()1340 status_t StagefrightRecorder::setupMPEG2TSRecording() {
1341     CHECK_EQ(mOutputFormat, OUTPUT_FORMAT_MPEG2TS);
1342 
1343     sp<MediaWriter> writer = new MPEG2TSWriter(mOutputFd);
1344 
1345     if (mAudioSource != AUDIO_SOURCE_CNT) {
1346         if (mAudioEncoder != AUDIO_ENCODER_AAC &&
1347             mAudioEncoder != AUDIO_ENCODER_HE_AAC &&
1348             mAudioEncoder != AUDIO_ENCODER_AAC_ELD) {
1349             return ERROR_UNSUPPORTED;
1350         }
1351 
1352         status_t err = setupAudioEncoder(writer);
1353 
1354         if (err != OK) {
1355             return err;
1356         }
1357     }
1358 
1359     if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1360         if (mVideoEncoder != VIDEO_ENCODER_H264) {
1361             ALOGE("MPEG2TS recording only supports H.264 encoding!");
1362             return ERROR_UNSUPPORTED;
1363         }
1364 
1365         sp<MediaSource> mediaSource;
1366         status_t err = setupMediaSource(&mediaSource);
1367         if (err != OK) {
1368             return err;
1369         }
1370 
1371         sp<MediaCodecSource> encoder;
1372         err = setupVideoEncoder(mediaSource, &encoder);
1373 
1374         if (err != OK) {
1375             return err;
1376         }
1377 
1378         writer->addSource(encoder);
1379         mVideoEncoderSource = encoder;
1380     }
1381 
1382     if (mMaxFileDurationUs != 0) {
1383         writer->setMaxFileDuration(mMaxFileDurationUs);
1384     }
1385 
1386     if (mMaxFileSizeBytes != 0) {
1387         writer->setMaxFileSize(mMaxFileSizeBytes);
1388     }
1389 
1390     mWriter = writer;
1391 
1392     return OK;
1393 }
1394 
clipVideoFrameRate()1395 void StagefrightRecorder::clipVideoFrameRate() {
1396     ALOGV("clipVideoFrameRate: encoder %d", mVideoEncoder);
1397     if (mFrameRate == -1) {
1398         mFrameRate = mEncoderProfiles->getCamcorderProfileParamByName(
1399                 "vid.fps", mCameraId, CAMCORDER_QUALITY_LOW);
1400         ALOGW("Using default video fps %d", mFrameRate);
1401     }
1402 
1403     int minFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1404                         "enc.vid.fps.min", mVideoEncoder);
1405     int maxFrameRate = mEncoderProfiles->getVideoEncoderParamByName(
1406                         "enc.vid.fps.max", mVideoEncoder);
1407     if (mFrameRate < minFrameRate && minFrameRate != -1) {
1408         ALOGW("Intended video encoding frame rate (%d fps) is too small"
1409              " and will be set to (%d fps)", mFrameRate, minFrameRate);
1410         mFrameRate = minFrameRate;
1411     } else if (mFrameRate > maxFrameRate && maxFrameRate != -1) {
1412         ALOGW("Intended video encoding frame rate (%d fps) is too large"
1413              " and will be set to (%d fps)", mFrameRate, maxFrameRate);
1414         mFrameRate = maxFrameRate;
1415     }
1416 }
1417 
clipVideoBitRate()1418 void StagefrightRecorder::clipVideoBitRate() {
1419     ALOGV("clipVideoBitRate: encoder %d", mVideoEncoder);
1420     int minBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1421                         "enc.vid.bps.min", mVideoEncoder);
1422     int maxBitRate = mEncoderProfiles->getVideoEncoderParamByName(
1423                         "enc.vid.bps.max", mVideoEncoder);
1424     if (mVideoBitRate < minBitRate && minBitRate != -1) {
1425         ALOGW("Intended video encoding bit rate (%d bps) is too small"
1426              " and will be set to (%d bps)", mVideoBitRate, minBitRate);
1427         mVideoBitRate = minBitRate;
1428     } else if (mVideoBitRate > maxBitRate && maxBitRate != -1) {
1429         ALOGW("Intended video encoding bit rate (%d bps) is too large"
1430              " and will be set to (%d bps)", mVideoBitRate, maxBitRate);
1431         mVideoBitRate = maxBitRate;
1432     }
1433 }
1434 
clipVideoFrameWidth()1435 void StagefrightRecorder::clipVideoFrameWidth() {
1436     ALOGV("clipVideoFrameWidth: encoder %d", mVideoEncoder);
1437     int minFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1438                         "enc.vid.width.min", mVideoEncoder);
1439     int maxFrameWidth = mEncoderProfiles->getVideoEncoderParamByName(
1440                         "enc.vid.width.max", mVideoEncoder);
1441     if (mVideoWidth < minFrameWidth && minFrameWidth != -1) {
1442         ALOGW("Intended video encoding frame width (%d) is too small"
1443              " and will be set to (%d)", mVideoWidth, minFrameWidth);
1444         mVideoWidth = minFrameWidth;
1445     } else if (mVideoWidth > maxFrameWidth && maxFrameWidth != -1) {
1446         ALOGW("Intended video encoding frame width (%d) is too large"
1447              " and will be set to (%d)", mVideoWidth, maxFrameWidth);
1448         mVideoWidth = maxFrameWidth;
1449     }
1450 }
1451 
checkVideoEncoderCapabilities()1452 status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
1453     if (!mCaptureFpsEnable) {
1454         // Dont clip for time lapse capture as encoder will have enough
1455         // time to encode because of slow capture rate of time lapse.
1456         clipVideoBitRate();
1457         clipVideoFrameRate();
1458         clipVideoFrameWidth();
1459         clipVideoFrameHeight();
1460         setDefaultProfileIfNecessary();
1461     }
1462     return OK;
1463 }
1464 
1465 // Set to use AVC baseline profile if the encoding parameters matches
1466 // CAMCORDER_QUALITY_LOW profile; this is for the sake of MMS service.
setDefaultProfileIfNecessary()1467 void StagefrightRecorder::setDefaultProfileIfNecessary() {
1468     ALOGV("setDefaultProfileIfNecessary");
1469 
1470     camcorder_quality quality = CAMCORDER_QUALITY_LOW;
1471 
1472     int64_t durationUs   = mEncoderProfiles->getCamcorderProfileParamByName(
1473                                 "duration", mCameraId, quality) * 1000000LL;
1474 
1475     int fileFormat       = mEncoderProfiles->getCamcorderProfileParamByName(
1476                                 "file.format", mCameraId, quality);
1477 
1478     int videoCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1479                                 "vid.codec", mCameraId, quality);
1480 
1481     int videoBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1482                                 "vid.bps", mCameraId, quality);
1483 
1484     int videoFrameRate   = mEncoderProfiles->getCamcorderProfileParamByName(
1485                                 "vid.fps", mCameraId, quality);
1486 
1487     int videoFrameWidth  = mEncoderProfiles->getCamcorderProfileParamByName(
1488                                 "vid.width", mCameraId, quality);
1489 
1490     int videoFrameHeight = mEncoderProfiles->getCamcorderProfileParamByName(
1491                                 "vid.height", mCameraId, quality);
1492 
1493     int audioCodec       = mEncoderProfiles->getCamcorderProfileParamByName(
1494                                 "aud.codec", mCameraId, quality);
1495 
1496     int audioBitRate     = mEncoderProfiles->getCamcorderProfileParamByName(
1497                                 "aud.bps", mCameraId, quality);
1498 
1499     int audioSampleRate  = mEncoderProfiles->getCamcorderProfileParamByName(
1500                                 "aud.hz", mCameraId, quality);
1501 
1502     int audioChannels    = mEncoderProfiles->getCamcorderProfileParamByName(
1503                                 "aud.ch", mCameraId, quality);
1504 
1505     if (durationUs == mMaxFileDurationUs &&
1506         fileFormat == mOutputFormat &&
1507         videoCodec == mVideoEncoder &&
1508         videoBitRate == mVideoBitRate &&
1509         videoFrameRate == mFrameRate &&
1510         videoFrameWidth == mVideoWidth &&
1511         videoFrameHeight == mVideoHeight &&
1512         audioCodec == mAudioEncoder &&
1513         audioBitRate == mAudioBitRate &&
1514         audioSampleRate == mSampleRate &&
1515         audioChannels == mAudioChannels) {
1516         if (videoCodec == VIDEO_ENCODER_H264) {
1517             ALOGI("Force to use AVC baseline profile");
1518             setParamVideoEncoderProfile(OMX_VIDEO_AVCProfileBaseline);
1519             // set 0 for invalid levels - this will be rejected by the
1520             // codec if it cannot handle it during configure
1521             setParamVideoEncoderLevel(ACodec::getAVCLevelFor(
1522                     videoFrameWidth, videoFrameHeight, videoFrameRate, videoBitRate));
1523         }
1524     }
1525 }
1526 
setDefaultVideoEncoderIfNecessary()1527 void StagefrightRecorder::setDefaultVideoEncoderIfNecessary() {
1528     if (mVideoEncoder == VIDEO_ENCODER_DEFAULT) {
1529         if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1530             // default to VP8 for WEBM recording
1531             mVideoEncoder = VIDEO_ENCODER_VP8;
1532         } else {
1533             // pick the default encoder for CAMCORDER_QUALITY_LOW
1534             int videoCodec = mEncoderProfiles->getCamcorderProfileParamByName(
1535                     "vid.codec", mCameraId, CAMCORDER_QUALITY_LOW);
1536 
1537             if (videoCodec > VIDEO_ENCODER_DEFAULT &&
1538                 videoCodec < VIDEO_ENCODER_LIST_END) {
1539                 mVideoEncoder = (video_encoder)videoCodec;
1540             } else {
1541                 // default to H.264 if camcorder profile not available
1542                 mVideoEncoder = VIDEO_ENCODER_H264;
1543             }
1544         }
1545     }
1546 }
1547 
checkAudioEncoderCapabilities()1548 status_t StagefrightRecorder::checkAudioEncoderCapabilities() {
1549     clipAudioBitRate();
1550     clipAudioSampleRate();
1551     clipNumberOfAudioChannels();
1552     return OK;
1553 }
1554 
clipAudioBitRate()1555 void StagefrightRecorder::clipAudioBitRate() {
1556     ALOGV("clipAudioBitRate: encoder %d", mAudioEncoder);
1557 
1558     int minAudioBitRate =
1559             mEncoderProfiles->getAudioEncoderParamByName(
1560                 "enc.aud.bps.min", mAudioEncoder);
1561     if (minAudioBitRate != -1 && mAudioBitRate < minAudioBitRate) {
1562         ALOGW("Intended audio encoding bit rate (%d) is too small"
1563             " and will be set to (%d)", mAudioBitRate, minAudioBitRate);
1564         mAudioBitRate = minAudioBitRate;
1565     }
1566 
1567     int maxAudioBitRate =
1568             mEncoderProfiles->getAudioEncoderParamByName(
1569                 "enc.aud.bps.max", mAudioEncoder);
1570     if (maxAudioBitRate != -1 && mAudioBitRate > maxAudioBitRate) {
1571         ALOGW("Intended audio encoding bit rate (%d) is too large"
1572             " and will be set to (%d)", mAudioBitRate, maxAudioBitRate);
1573         mAudioBitRate = maxAudioBitRate;
1574     }
1575 }
1576 
clipAudioSampleRate()1577 void StagefrightRecorder::clipAudioSampleRate() {
1578     ALOGV("clipAudioSampleRate: encoder %d", mAudioEncoder);
1579 
1580     int minSampleRate =
1581             mEncoderProfiles->getAudioEncoderParamByName(
1582                 "enc.aud.hz.min", mAudioEncoder);
1583     if (minSampleRate != -1 && mSampleRate < minSampleRate) {
1584         ALOGW("Intended audio sample rate (%d) is too small"
1585             " and will be set to (%d)", mSampleRate, minSampleRate);
1586         mSampleRate = minSampleRate;
1587     }
1588 
1589     int maxSampleRate =
1590             mEncoderProfiles->getAudioEncoderParamByName(
1591                 "enc.aud.hz.max", mAudioEncoder);
1592     if (maxSampleRate != -1 && mSampleRate > maxSampleRate) {
1593         ALOGW("Intended audio sample rate (%d) is too large"
1594             " and will be set to (%d)", mSampleRate, maxSampleRate);
1595         mSampleRate = maxSampleRate;
1596     }
1597 }
1598 
clipNumberOfAudioChannels()1599 void StagefrightRecorder::clipNumberOfAudioChannels() {
1600     ALOGV("clipNumberOfAudioChannels: encoder %d", mAudioEncoder);
1601 
1602     int minChannels =
1603             mEncoderProfiles->getAudioEncoderParamByName(
1604                 "enc.aud.ch.min", mAudioEncoder);
1605     if (minChannels != -1 && mAudioChannels < minChannels) {
1606         ALOGW("Intended number of audio channels (%d) is too small"
1607             " and will be set to (%d)", mAudioChannels, minChannels);
1608         mAudioChannels = minChannels;
1609     }
1610 
1611     int maxChannels =
1612             mEncoderProfiles->getAudioEncoderParamByName(
1613                 "enc.aud.ch.max", mAudioEncoder);
1614     if (maxChannels != -1 && mAudioChannels > maxChannels) {
1615         ALOGW("Intended number of audio channels (%d) is too large"
1616             " and will be set to (%d)", mAudioChannels, maxChannels);
1617         mAudioChannels = maxChannels;
1618     }
1619 }
1620 
clipVideoFrameHeight()1621 void StagefrightRecorder::clipVideoFrameHeight() {
1622     ALOGV("clipVideoFrameHeight: encoder %d", mVideoEncoder);
1623     int minFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1624                         "enc.vid.height.min", mVideoEncoder);
1625     int maxFrameHeight = mEncoderProfiles->getVideoEncoderParamByName(
1626                         "enc.vid.height.max", mVideoEncoder);
1627     if (minFrameHeight != -1 && mVideoHeight < minFrameHeight) {
1628         ALOGW("Intended video encoding frame height (%d) is too small"
1629              " and will be set to (%d)", mVideoHeight, minFrameHeight);
1630         mVideoHeight = minFrameHeight;
1631     } else if (maxFrameHeight != -1 && mVideoHeight > maxFrameHeight) {
1632         ALOGW("Intended video encoding frame height (%d) is too large"
1633              " and will be set to (%d)", mVideoHeight, maxFrameHeight);
1634         mVideoHeight = maxFrameHeight;
1635     }
1636 }
1637 
1638 // Set up the appropriate MediaSource depending on the chosen option
setupMediaSource(sp<MediaSource> * mediaSource)1639 status_t StagefrightRecorder::setupMediaSource(
1640                       sp<MediaSource> *mediaSource) {
1641     if (mVideoSource == VIDEO_SOURCE_DEFAULT
1642             || mVideoSource == VIDEO_SOURCE_CAMERA) {
1643         sp<CameraSource> cameraSource;
1644         status_t err = setupCameraSource(&cameraSource);
1645         if (err != OK) {
1646             return err;
1647         }
1648         *mediaSource = cameraSource;
1649     } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1650         *mediaSource = NULL;
1651     } else {
1652         return INVALID_OPERATION;
1653     }
1654     return OK;
1655 }
1656 
setupCameraSource(sp<CameraSource> * cameraSource)1657 status_t StagefrightRecorder::setupCameraSource(
1658         sp<CameraSource> *cameraSource) {
1659     status_t err = OK;
1660     if ((err = checkVideoEncoderCapabilities()) != OK) {
1661         return err;
1662     }
1663     Size videoSize;
1664     videoSize.width = mVideoWidth;
1665     videoSize.height = mVideoHeight;
1666     if (mCaptureFpsEnable) {
1667         if (!(mCaptureFps > 0.)) {
1668             ALOGE("Invalid mCaptureFps value: %lf", mCaptureFps);
1669             return BAD_VALUE;
1670         }
1671 
1672         mCameraSourceTimeLapse = CameraSourceTimeLapse::CreateFromCamera(
1673                 mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1674                 videoSize, mFrameRate, mPreviewSurface,
1675                 std::llround(1e6 / mCaptureFps));
1676         *cameraSource = mCameraSourceTimeLapse;
1677     } else {
1678         *cameraSource = CameraSource::CreateFromCamera(
1679                 mCamera, mCameraProxy, mCameraId, mClientName, mClientUid, mClientPid,
1680                 videoSize, mFrameRate,
1681                 mPreviewSurface);
1682     }
1683     mCamera.clear();
1684     mCameraProxy.clear();
1685     if (*cameraSource == NULL) {
1686         return UNKNOWN_ERROR;
1687     }
1688 
1689     if ((*cameraSource)->initCheck() != OK) {
1690         (*cameraSource).clear();
1691         *cameraSource = NULL;
1692         return NO_INIT;
1693     }
1694 
1695     // When frame rate is not set, the actual frame rate will be set to
1696     // the current frame rate being used.
1697     if (mFrameRate == -1) {
1698         int32_t frameRate = 0;
1699         CHECK ((*cameraSource)->getFormat()->findInt32(
1700                     kKeyFrameRate, &frameRate));
1701         ALOGI("Frame rate is not explicitly set. Use the current frame "
1702              "rate (%d fps)", frameRate);
1703         mFrameRate = frameRate;
1704     }
1705 
1706     CHECK(mFrameRate != -1);
1707 
1708     mMetaDataStoredInVideoBuffers =
1709         (*cameraSource)->metaDataStoredInVideoBuffers();
1710 
1711     return OK;
1712 }
1713 
setupVideoEncoder(const sp<MediaSource> & cameraSource,sp<MediaCodecSource> * source)1714 status_t StagefrightRecorder::setupVideoEncoder(
1715         const sp<MediaSource> &cameraSource,
1716         sp<MediaCodecSource> *source) {
1717     source->clear();
1718 
1719     sp<AMessage> format = new AMessage();
1720 
1721     switch (mVideoEncoder) {
1722         case VIDEO_ENCODER_H263:
1723             format->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
1724             break;
1725 
1726         case VIDEO_ENCODER_MPEG_4_SP:
1727             format->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
1728             break;
1729 
1730         case VIDEO_ENCODER_H264:
1731             format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
1732             break;
1733 
1734         case VIDEO_ENCODER_VP8:
1735             format->setString("mime", MEDIA_MIMETYPE_VIDEO_VP8);
1736             break;
1737 
1738         case VIDEO_ENCODER_HEVC:
1739             format->setString("mime", MEDIA_MIMETYPE_VIDEO_HEVC);
1740             break;
1741 
1742         default:
1743             CHECK(!"Should not be here, unsupported video encoding.");
1744             break;
1745     }
1746 
1747     // log video mime type for media metrics
1748     if (mMetricsItem != NULL) {
1749         AString videomime;
1750         if (format->findString("mime", &videomime)) {
1751             mMetricsItem->setCString(kRecorderVideoMime, videomime.c_str());
1752         }
1753     }
1754 
1755     if (cameraSource != NULL) {
1756         sp<MetaData> meta = cameraSource->getFormat();
1757 
1758         int32_t width, height, stride, sliceHeight, colorFormat;
1759         CHECK(meta->findInt32(kKeyWidth, &width));
1760         CHECK(meta->findInt32(kKeyHeight, &height));
1761         CHECK(meta->findInt32(kKeyStride, &stride));
1762         CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
1763         CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
1764 
1765         format->setInt32("width", width);
1766         format->setInt32("height", height);
1767         format->setInt32("stride", stride);
1768         format->setInt32("slice-height", sliceHeight);
1769         format->setInt32("color-format", colorFormat);
1770     } else {
1771         format->setInt32("width", mVideoWidth);
1772         format->setInt32("height", mVideoHeight);
1773         format->setInt32("stride", mVideoWidth);
1774         format->setInt32("slice-height", mVideoHeight);
1775         format->setInt32("color-format", OMX_COLOR_FormatAndroidOpaque);
1776 
1777         // set up time lapse/slow motion for surface source
1778         if (mCaptureFpsEnable) {
1779             if (!(mCaptureFps > 0.)) {
1780                 ALOGE("Invalid mCaptureFps value: %lf", mCaptureFps);
1781                 return BAD_VALUE;
1782             }
1783             format->setDouble("time-lapse-fps", mCaptureFps);
1784         }
1785     }
1786 
1787     format->setInt32("bitrate", mVideoBitRate);
1788     format->setInt32("frame-rate", mFrameRate);
1789     format->setInt32("i-frame-interval", mIFramesIntervalSec);
1790 
1791     if (mVideoTimeScale > 0) {
1792         format->setInt32("time-scale", mVideoTimeScale);
1793     }
1794     if (mVideoEncoderProfile != -1) {
1795         format->setInt32("profile", mVideoEncoderProfile);
1796     }
1797     if (mVideoEncoderLevel != -1) {
1798         format->setInt32("level", mVideoEncoderLevel);
1799     }
1800 
1801     uint32_t tsLayers = 1;
1802     bool preferBFrames = true; // we like B-frames as it produces better quality per bitrate
1803     format->setInt32("priority", 0 /* realtime */);
1804     float maxPlaybackFps = mFrameRate; // assume video is only played back at normal speed
1805 
1806     if (mCaptureFpsEnable) {
1807         format->setFloat("operating-rate", mCaptureFps);
1808 
1809         // enable layering for all time lapse and high frame rate recordings
1810         if (mFrameRate / mCaptureFps >= 1.9) { // time lapse
1811             preferBFrames = false;
1812             tsLayers = 2; // use at least two layers as resulting video will likely be sped up
1813         } else if (mCaptureFps > maxPlaybackFps) { // slow-mo
1814             maxPlaybackFps = mCaptureFps; // assume video will be played back at full capture speed
1815             preferBFrames = false;
1816         }
1817     }
1818 
1819     // Enable temporal layering if the expected (max) playback frame rate is greater than ~11% of
1820     // the minimum display refresh rate on a typical device. Add layers until the base layer falls
1821     // under this limit. Allow device manufacturers to override this limit.
1822 
1823     // TODO: make this configurable by the application
1824     std::string maxBaseLayerFpsProperty =
1825         ::android::base::GetProperty("ro.media.recorder-max-base-layer-fps", "");
1826     float maxBaseLayerFps = (float)::atof(maxBaseLayerFpsProperty.c_str());
1827     // TRICKY: use !> to fix up any NaN values
1828     if (!(maxBaseLayerFps >= kMinTypicalDisplayRefreshingRate / 0.9)) {
1829         maxBaseLayerFps = kMinTypicalDisplayRefreshingRate / 0.9;
1830     }
1831 
1832     for (uint32_t tryLayers = 1; tryLayers <= kMaxNumVideoTemporalLayers; ++tryLayers) {
1833         if (tryLayers > tsLayers) {
1834             tsLayers = tryLayers;
1835         }
1836         // keep going until the base layer fps falls below the typical display refresh rate
1837         float baseLayerFps = maxPlaybackFps / (1 << (tryLayers - 1));
1838         if (baseLayerFps < maxBaseLayerFps) {
1839             break;
1840         }
1841     }
1842 
1843     if (tsLayers > 1) {
1844         uint32_t bLayers = std::min(2u, tsLayers - 1); // use up-to 2 B-layers
1845         uint32_t pLayers = tsLayers - bLayers;
1846         format->setString(
1847                 "ts-schema", AStringPrintf("android.generic.%u+%u", pLayers, bLayers));
1848 
1849         // TODO: some encoders do not support B-frames with temporal layering, and we have a
1850         // different preference based on use-case. We could move this into camera profiles.
1851         format->setInt32("android._prefer-b-frames", preferBFrames);
1852     }
1853 
1854     if (mMetaDataStoredInVideoBuffers != kMetadataBufferTypeInvalid) {
1855         format->setInt32("android._input-metadata-buffer-type", mMetaDataStoredInVideoBuffers);
1856     }
1857 
1858     uint32_t flags = 0;
1859     if (cameraSource == NULL) {
1860         flags |= MediaCodecSource::FLAG_USE_SURFACE_INPUT;
1861     } else {
1862         // require dataspace setup even if not using surface input
1863         format->setInt32("android._using-recorder", 1);
1864     }
1865 
1866     sp<MediaCodecSource> encoder = MediaCodecSource::Create(
1867             mLooper, format, cameraSource, mPersistentSurface, flags);
1868     if (encoder == NULL) {
1869         ALOGE("Failed to create video encoder");
1870         // When the encoder fails to be created, we need
1871         // release the camera source due to the camera's lock
1872         // and unlock mechanism.
1873         if (cameraSource != NULL) {
1874             cameraSource->stop();
1875         }
1876         return UNKNOWN_ERROR;
1877     }
1878 
1879     if (cameraSource == NULL) {
1880         mGraphicBufferProducer = encoder->getGraphicBufferProducer();
1881     }
1882 
1883     *source = encoder;
1884 
1885     return OK;
1886 }
1887 
setupAudioEncoder(const sp<MediaWriter> & writer)1888 status_t StagefrightRecorder::setupAudioEncoder(const sp<MediaWriter>& writer) {
1889     status_t status = BAD_VALUE;
1890     if (OK != (status = checkAudioEncoderCapabilities())) {
1891         return status;
1892     }
1893 
1894     switch(mAudioEncoder) {
1895         case AUDIO_ENCODER_AMR_NB:
1896         case AUDIO_ENCODER_AMR_WB:
1897         case AUDIO_ENCODER_AAC:
1898         case AUDIO_ENCODER_HE_AAC:
1899         case AUDIO_ENCODER_AAC_ELD:
1900         case AUDIO_ENCODER_OPUS:
1901             break;
1902 
1903         default:
1904             ALOGE("Unsupported audio encoder: %d", mAudioEncoder);
1905             return UNKNOWN_ERROR;
1906     }
1907 
1908     sp<MediaCodecSource> audioEncoder = createAudioSource();
1909     if (audioEncoder == NULL) {
1910         return UNKNOWN_ERROR;
1911     }
1912 
1913     writer->addSource(audioEncoder);
1914     mAudioEncoderSource = audioEncoder;
1915     return OK;
1916 }
1917 
setupMPEG4orWEBMRecording()1918 status_t StagefrightRecorder::setupMPEG4orWEBMRecording() {
1919     mWriter.clear();
1920     mTotalBitRate = 0;
1921 
1922     status_t err = OK;
1923     sp<MediaWriter> writer;
1924     sp<MPEG4Writer> mp4writer;
1925     if (mOutputFormat == OUTPUT_FORMAT_WEBM) {
1926         writer = new WebmWriter(mOutputFd);
1927     } else {
1928         writer = mp4writer = new MPEG4Writer(mOutputFd);
1929     }
1930 
1931     if (mVideoSource < VIDEO_SOURCE_LIST_END) {
1932         setDefaultVideoEncoderIfNecessary();
1933 
1934         sp<MediaSource> mediaSource;
1935         err = setupMediaSource(&mediaSource);
1936         if (err != OK) {
1937             return err;
1938         }
1939 
1940         sp<MediaCodecSource> encoder;
1941         err = setupVideoEncoder(mediaSource, &encoder);
1942         if (err != OK) {
1943             return err;
1944         }
1945 
1946         writer->addSource(encoder);
1947         mVideoEncoderSource = encoder;
1948         mTotalBitRate += mVideoBitRate;
1949     }
1950 
1951     // Audio source is added at the end if it exists.
1952     // This help make sure that the "recoding" sound is suppressed for
1953     // camcorder applications in the recorded files.
1954     // disable audio for time lapse recording
1955     const bool disableAudio = mCaptureFpsEnable && mCaptureFps < mFrameRate;
1956     if (!disableAudio && mAudioSource != AUDIO_SOURCE_CNT) {
1957         err = setupAudioEncoder(writer);
1958         if (err != OK) return err;
1959         mTotalBitRate += mAudioBitRate;
1960     }
1961 
1962     if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
1963         if (mCaptureFpsEnable) {
1964             mp4writer->setCaptureRate(mCaptureFps);
1965         }
1966 
1967         if (mInterleaveDurationUs > 0) {
1968             mp4writer->setInterleaveDuration(mInterleaveDurationUs);
1969         }
1970         if (mLongitudex10000 > -3600000 && mLatitudex10000 > -3600000) {
1971             mp4writer->setGeoData(mLatitudex10000, mLongitudex10000);
1972         }
1973     }
1974     if (mMaxFileDurationUs != 0) {
1975         writer->setMaxFileDuration(mMaxFileDurationUs);
1976     }
1977     if (mMaxFileSizeBytes != 0) {
1978         writer->setMaxFileSize(mMaxFileSizeBytes);
1979     }
1980     if (mVideoSource == VIDEO_SOURCE_DEFAULT
1981             || mVideoSource == VIDEO_SOURCE_CAMERA) {
1982         mStartTimeOffsetMs = mEncoderProfiles->getStartTimeOffsetMs(mCameraId);
1983     } else if (mVideoSource == VIDEO_SOURCE_SURFACE) {
1984         // surface source doesn't need large initial delay
1985         mStartTimeOffsetMs = 100;
1986     }
1987     if (mStartTimeOffsetMs > 0) {
1988         writer->setStartTimeOffsetMs(mStartTimeOffsetMs);
1989     }
1990 
1991     writer->setListener(mListener);
1992     mWriter = writer;
1993     return OK;
1994 }
1995 
setupMPEG4orWEBMMetaData(sp<MetaData> * meta)1996 void StagefrightRecorder::setupMPEG4orWEBMMetaData(sp<MetaData> *meta) {
1997     int64_t startTimeUs = systemTime() / 1000;
1998     (*meta)->setInt64(kKeyTime, startTimeUs);
1999     (*meta)->setInt32(kKeyFileType, mOutputFormat);
2000     (*meta)->setInt32(kKeyBitRate, mTotalBitRate);
2001     if (mMovieTimeScale > 0) {
2002         (*meta)->setInt32(kKeyTimeScale, mMovieTimeScale);
2003     }
2004     if (mOutputFormat != OUTPUT_FORMAT_WEBM) {
2005         if (mTrackEveryTimeDurationUs > 0) {
2006             (*meta)->setInt64(kKeyTrackTimeStatus, mTrackEveryTimeDurationUs);
2007         }
2008         if (mRotationDegrees != 0) {
2009             (*meta)->setInt32(kKeyRotation, mRotationDegrees);
2010         }
2011     }
2012     if (mOutputFormat == OUTPUT_FORMAT_MPEG_4 || mOutputFormat == OUTPUT_FORMAT_THREE_GPP) {
2013         (*meta)->setInt32(kKeyEmptyTrackMalFormed, true);
2014         (*meta)->setInt32(kKey4BitTrackIds, true);
2015     }
2016 }
2017 
pause()2018 status_t StagefrightRecorder::pause() {
2019     ALOGV("pause");
2020     if (!mStarted) {
2021         return INVALID_OPERATION;
2022     }
2023 
2024     // Already paused --- no-op.
2025     if (mPauseStartTimeUs != 0) {
2026         return OK;
2027     }
2028 
2029     mPauseStartTimeUs = systemTime() / 1000;
2030     sp<MetaData> meta = new MetaData;
2031     meta->setInt64(kKeyTime, mPauseStartTimeUs);
2032 
2033     if (mStartedRecordingUs != 0) {
2034         // should always be true
2035         int64_t recordingUs = mPauseStartTimeUs - mStartedRecordingUs;
2036         mDurationRecordedUs += recordingUs;
2037         mStartedRecordingUs = 0;
2038     }
2039 
2040     if (mAudioEncoderSource != NULL) {
2041         mAudioEncoderSource->pause();
2042     }
2043     if (mVideoEncoderSource != NULL) {
2044         mVideoEncoderSource->pause(meta.get());
2045     }
2046 
2047     return OK;
2048 }
2049 
resume()2050 status_t StagefrightRecorder::resume() {
2051     ALOGV("resume");
2052     if (!mStarted) {
2053         return INVALID_OPERATION;
2054     }
2055 
2056     // Not paused --- no-op.
2057     if (mPauseStartTimeUs == 0) {
2058         return OK;
2059     }
2060 
2061     int64_t resumeStartTimeUs = systemTime() / 1000;
2062 
2063     int64_t bufferStartTimeUs = 0;
2064     bool allSourcesStarted = true;
2065     for (const auto &source : { mAudioEncoderSource, mVideoEncoderSource }) {
2066         if (source == nullptr) {
2067             continue;
2068         }
2069         int64_t timeUs = source->getFirstSampleSystemTimeUs();
2070         if (timeUs < 0) {
2071             allSourcesStarted = false;
2072         }
2073         if (bufferStartTimeUs < timeUs) {
2074             bufferStartTimeUs = timeUs;
2075         }
2076     }
2077 
2078     if (allSourcesStarted) {
2079         if (mPauseStartTimeUs < bufferStartTimeUs) {
2080             mPauseStartTimeUs = bufferStartTimeUs;
2081         }
2082         // 30 ms buffer to avoid timestamp overlap
2083         mTotalPausedDurationUs += resumeStartTimeUs - mPauseStartTimeUs - 30000;
2084     }
2085     double timeOffset = -mTotalPausedDurationUs;
2086     if (mCaptureFpsEnable && (mVideoSource == VIDEO_SOURCE_CAMERA)) {
2087         timeOffset *= mCaptureFps / mFrameRate;
2088     }
2089     sp<MetaData> meta = new MetaData;
2090     meta->setInt64(kKeyTime, resumeStartTimeUs);
2091     for (const auto &source : { mAudioEncoderSource, mVideoEncoderSource }) {
2092         if (source == nullptr) {
2093             continue;
2094         }
2095         source->setInputBufferTimeOffset((int64_t)timeOffset);
2096         source->start(meta.get());
2097     }
2098 
2099 
2100     // sum info on pause duration
2101     // (ignore the 30msec of overlap adjustment factored into mTotalPausedDurationUs)
2102     int64_t pausedUs = resumeStartTimeUs - mPauseStartTimeUs;
2103     mDurationPausedUs += pausedUs;
2104     mNPauses++;
2105     // and a timestamp marking that we're back to recording....
2106     mStartedRecordingUs = resumeStartTimeUs;
2107 
2108     mPauseStartTimeUs = 0;
2109 
2110     return OK;
2111 }
2112 
stop()2113 status_t StagefrightRecorder::stop() {
2114     ALOGV("stop");
2115     Mutex::Autolock autolock(mLock);
2116     status_t err = OK;
2117 
2118     if (mCaptureFpsEnable && mCameraSourceTimeLapse != NULL) {
2119         mCameraSourceTimeLapse->startQuickReadReturns();
2120         mCameraSourceTimeLapse = NULL;
2121     }
2122 
2123     int64_t stopTimeUs = systemTime() / 1000;
2124     for (const auto &source : { mAudioEncoderSource, mVideoEncoderSource }) {
2125         if (source != nullptr && OK != source->setStopTimeUs(stopTimeUs)) {
2126             ALOGW("Failed to set stopTime %lld us for %s",
2127                     (long long)stopTimeUs, source->isVideo() ? "Video" : "Audio");
2128         }
2129     }
2130 
2131     if (mWriter != NULL) {
2132         err = mWriter->stop();
2133         mWriter.clear();
2134     }
2135 
2136     // account for the last 'segment' -- whether paused or recording
2137     if (mPauseStartTimeUs != 0) {
2138         // we were paused
2139         int64_t additive = stopTimeUs - mPauseStartTimeUs;
2140         mDurationPausedUs += additive;
2141         mNPauses++;
2142     } else if (mStartedRecordingUs != 0) {
2143         // we were recording
2144         int64_t additive = stopTimeUs - mStartedRecordingUs;
2145         mDurationRecordedUs += additive;
2146     } else {
2147         ALOGW("stop while neither recording nor paused");
2148     }
2149 
2150     flushAndResetMetrics(true);
2151 
2152     mDurationRecordedUs = 0;
2153     mDurationPausedUs = 0;
2154     mNPauses = 0;
2155     mTotalPausedDurationUs = 0;
2156     mPauseStartTimeUs = 0;
2157     mStartedRecordingUs = 0;
2158 
2159     mGraphicBufferProducer.clear();
2160     mPersistentSurface.clear();
2161     mAudioEncoderSource.clear();
2162     mVideoEncoderSource.clear();
2163 
2164     if (mOutputFd >= 0) {
2165         ::close(mOutputFd);
2166         mOutputFd = -1;
2167     }
2168 
2169     if (mStarted) {
2170         mStarted = false;
2171 
2172         uint32_t params = 0;
2173         if (mAudioSource != AUDIO_SOURCE_CNT) {
2174             params |= IMediaPlayerService::kBatteryDataTrackAudio;
2175         }
2176         if (mVideoSource != VIDEO_SOURCE_LIST_END) {
2177             params |= IMediaPlayerService::kBatteryDataTrackVideo;
2178         }
2179 
2180         addBatteryData(params);
2181     }
2182 
2183     return err;
2184 }
2185 
close()2186 status_t StagefrightRecorder::close() {
2187     ALOGV("close");
2188     stop();
2189 
2190     return OK;
2191 }
2192 
reset()2193 status_t StagefrightRecorder::reset() {
2194     ALOGV("reset");
2195     stop();
2196 
2197     // No audio or video source by default
2198     mAudioSource = (audio_source_t)AUDIO_SOURCE_CNT; // reset to invalid value
2199     mVideoSource = VIDEO_SOURCE_LIST_END;
2200 
2201     // Default parameters
2202     mOutputFormat  = OUTPUT_FORMAT_THREE_GPP;
2203     mAudioEncoder  = AUDIO_ENCODER_AMR_NB;
2204     mVideoEncoder  = VIDEO_ENCODER_DEFAULT;
2205     mVideoWidth    = 176;
2206     mVideoHeight   = 144;
2207     mFrameRate     = -1;
2208     mVideoBitRate  = 192000;
2209     mSampleRate    = 8000;
2210     mAudioChannels = 1;
2211     mAudioBitRate  = 12200;
2212     mInterleaveDurationUs = 0;
2213     mIFramesIntervalSec = 1;
2214     mAudioSourceNode = 0;
2215     mUse64BitFileOffset = false;
2216     mMovieTimeScale  = -1;
2217     mAudioTimeScale  = -1;
2218     mVideoTimeScale  = -1;
2219     mCameraId        = 0;
2220     mStartTimeOffsetMs = -1;
2221     mVideoEncoderProfile = -1;
2222     mVideoEncoderLevel   = -1;
2223     mMaxFileDurationUs = 0;
2224     mMaxFileSizeBytes = 0;
2225     mTrackEveryTimeDurationUs = 0;
2226     mCaptureFpsEnable = false;
2227     mCaptureFps = -1.0;
2228     mCameraSourceTimeLapse = NULL;
2229     mMetaDataStoredInVideoBuffers = kMetadataBufferTypeInvalid;
2230     mEncoderProfiles = MediaProfiles::getInstance();
2231     mRotationDegrees = 0;
2232     mLatitudex10000 = -3600000;
2233     mLongitudex10000 = -3600000;
2234     mTotalBitRate = 0;
2235 
2236     // tracking how long we recorded.
2237     mDurationRecordedUs = 0;
2238     mStartedRecordingUs = 0;
2239     mDurationPausedUs = 0;
2240     mNPauses = 0;
2241 
2242     mOutputFd = -1;
2243 
2244     return OK;
2245 }
2246 
getMaxAmplitude(int * max)2247 status_t StagefrightRecorder::getMaxAmplitude(int *max) {
2248     ALOGV("getMaxAmplitude");
2249 
2250     if (max == NULL) {
2251         ALOGE("Null pointer argument");
2252         return BAD_VALUE;
2253     }
2254 
2255     if (mAudioSourceNode != 0) {
2256         *max = mAudioSourceNode->getMaxAmplitude();
2257     } else {
2258         *max = 0;
2259     }
2260 
2261     return OK;
2262 }
2263 
getMetrics(Parcel * reply)2264 status_t StagefrightRecorder::getMetrics(Parcel *reply) {
2265     ALOGV("StagefrightRecorder::getMetrics");
2266 
2267     if (reply == NULL) {
2268         ALOGE("Null pointer argument");
2269         return BAD_VALUE;
2270     }
2271 
2272     if (mMetricsItem == NULL) {
2273         return UNKNOWN_ERROR;
2274     }
2275 
2276     updateMetrics();
2277     mMetricsItem->writeToParcel(reply);
2278     return OK;
2279 }
2280 
setInputDevice(audio_port_handle_t deviceId)2281 status_t StagefrightRecorder::setInputDevice(audio_port_handle_t deviceId) {
2282     ALOGV("setInputDevice");
2283 
2284     if (mSelectedDeviceId != deviceId) {
2285         mSelectedDeviceId = deviceId;
2286         if (mAudioSourceNode != 0) {
2287             return mAudioSourceNode->setInputDevice(deviceId);
2288         }
2289     }
2290     return NO_ERROR;
2291 }
2292 
getRoutedDeviceId(audio_port_handle_t * deviceId)2293 status_t StagefrightRecorder::getRoutedDeviceId(audio_port_handle_t* deviceId) {
2294     ALOGV("getRoutedDeviceId");
2295 
2296     if (mAudioSourceNode != 0) {
2297         status_t status = mAudioSourceNode->getRoutedDeviceId(deviceId);
2298         return status;
2299     }
2300     return NO_INIT;
2301 }
2302 
setAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)2303 void StagefrightRecorder::setAudioDeviceCallback(
2304         const sp<AudioSystem::AudioDeviceCallback>& callback) {
2305     mAudioDeviceCallback = callback;
2306 }
2307 
enableAudioDeviceCallback(bool enabled)2308 status_t StagefrightRecorder::enableAudioDeviceCallback(bool enabled) {
2309     mDeviceCallbackEnabled = enabled;
2310     sp<AudioSystem::AudioDeviceCallback> callback = mAudioDeviceCallback.promote();
2311     if (mAudioSourceNode != 0 && callback != 0) {
2312         if (enabled) {
2313             return mAudioSourceNode->addAudioDeviceCallback(callback);
2314         } else {
2315             return mAudioSourceNode->removeAudioDeviceCallback(callback);
2316         }
2317     }
2318     return NO_ERROR;
2319 }
2320 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)2321 status_t StagefrightRecorder::getActiveMicrophones(
2322         std::vector<media::MicrophoneInfo>* activeMicrophones) {
2323     if (mAudioSourceNode != 0) {
2324         return mAudioSourceNode->getActiveMicrophones(activeMicrophones);
2325     }
2326     return NO_INIT;
2327 }
2328 
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)2329 status_t StagefrightRecorder::setPreferredMicrophoneDirection(audio_microphone_direction_t direction) {
2330     ALOGV("setPreferredMicrophoneDirection(%d)", direction);
2331     mSelectedMicDirection = direction;
2332     if (mAudioSourceNode != 0) {
2333         return mAudioSourceNode->setPreferredMicrophoneDirection(direction);
2334     }
2335     return NO_INIT;
2336 }
2337 
setPreferredMicrophoneFieldDimension(float zoom)2338 status_t StagefrightRecorder::setPreferredMicrophoneFieldDimension(float zoom) {
2339     ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
2340     mSelectedMicFieldDimension = zoom;
2341     if (mAudioSourceNode != 0) {
2342         return mAudioSourceNode->setPreferredMicrophoneFieldDimension(zoom);
2343     }
2344     return NO_INIT;
2345 }
2346 
getPortId(audio_port_handle_t * portId) const2347 status_t StagefrightRecorder::getPortId(audio_port_handle_t *portId) const {
2348     if (mAudioSourceNode != 0) {
2349         return mAudioSourceNode->getPortId(portId);
2350     }
2351     return NO_INIT;
2352 }
2353 
dump(int fd,const Vector<String16> & args) const2354 status_t StagefrightRecorder::dump(
2355         int fd, const Vector<String16>& args) const {
2356     ALOGV("dump");
2357     Mutex::Autolock autolock(mLock);
2358     const size_t SIZE = 256;
2359     char buffer[SIZE];
2360     String8 result;
2361     if (mWriter != 0) {
2362         mWriter->dump(fd, args);
2363     } else {
2364         snprintf(buffer, SIZE, "   No file writer\n");
2365         result.append(buffer);
2366     }
2367     snprintf(buffer, SIZE, "   Recorder: %p\n", this);
2368     snprintf(buffer, SIZE, "   Output file (fd %d):\n", mOutputFd);
2369     result.append(buffer);
2370     snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
2371     result.append(buffer);
2372     snprintf(buffer, SIZE, "     Max file size (bytes): %" PRId64 "\n", mMaxFileSizeBytes);
2373     result.append(buffer);
2374     snprintf(buffer, SIZE, "     Max file duration (us): %" PRId64 "\n", mMaxFileDurationUs);
2375     result.append(buffer);
2376     snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
2377     result.append(buffer);
2378     snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
2379     result.append(buffer);
2380     snprintf(buffer, SIZE, "     Progress notification: %" PRId64 " us\n", mTrackEveryTimeDurationUs);
2381     result.append(buffer);
2382     snprintf(buffer, SIZE, "   Audio\n");
2383     result.append(buffer);
2384     snprintf(buffer, SIZE, "     Source: %d\n", mAudioSource);
2385     result.append(buffer);
2386     snprintf(buffer, SIZE, "     Encoder: %d\n", mAudioEncoder);
2387     result.append(buffer);
2388     snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mAudioBitRate);
2389     result.append(buffer);
2390     snprintf(buffer, SIZE, "     Sampling rate (hz): %d\n", mSampleRate);
2391     result.append(buffer);
2392     snprintf(buffer, SIZE, "     Number of channels: %d\n", mAudioChannels);
2393     result.append(buffer);
2394     snprintf(buffer, SIZE, "     Max amplitude: %d\n", mAudioSourceNode == 0? 0: mAudioSourceNode->getMaxAmplitude());
2395     result.append(buffer);
2396     snprintf(buffer, SIZE, "   Video\n");
2397     result.append(buffer);
2398     snprintf(buffer, SIZE, "     Source: %d\n", mVideoSource);
2399     result.append(buffer);
2400     snprintf(buffer, SIZE, "     Camera Id: %d\n", mCameraId);
2401     result.append(buffer);
2402     snprintf(buffer, SIZE, "     Start time offset (ms): %d\n", mStartTimeOffsetMs);
2403     result.append(buffer);
2404     snprintf(buffer, SIZE, "     Encoder: %d\n", mVideoEncoder);
2405     result.append(buffer);
2406     snprintf(buffer, SIZE, "     Encoder profile: %d\n", mVideoEncoderProfile);
2407     result.append(buffer);
2408     snprintf(buffer, SIZE, "     Encoder level: %d\n", mVideoEncoderLevel);
2409     result.append(buffer);
2410     snprintf(buffer, SIZE, "     I frames interval (s): %d\n", mIFramesIntervalSec);
2411     result.append(buffer);
2412     snprintf(buffer, SIZE, "     Frame size (pixels): %dx%d\n", mVideoWidth, mVideoHeight);
2413     result.append(buffer);
2414     snprintf(buffer, SIZE, "     Frame rate (fps): %d\n", mFrameRate);
2415     result.append(buffer);
2416     snprintf(buffer, SIZE, "     Bit rate (bps): %d\n", mVideoBitRate);
2417     result.append(buffer);
2418     ::write(fd, result.string(), result.size());
2419     return OK;
2420 }
2421 }  // namespace android
2422