1/*
2**
3** Copyright (C) 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#define LOG_TAG "CameraService"
19//#define LOG_NDEBUG 0
20
21#include <stdio.h>
22#include <sys/types.h>
23#include <pthread.h>
24
25#include <binder/IPCThreadState.h>
26#include <binder/IServiceManager.h>
27#include <binder/MemoryBase.h>
28#include <binder/MemoryHeapBase.h>
29#include <cutils/atomic.h>
30#include <cutils/properties.h>
31#include <gui/SurfaceTextureClient.h>
32#include <gui/Surface.h>
33#include <hardware/hardware.h>
34#include <media/AudioSystem.h>
35#include <media/mediaplayer.h>
36#include <utils/Errors.h>
37#include <utils/Log.h>
38#include <utils/String16.h>
39
40#include "CameraService.h"
41#include "CameraHardwareInterface.h"
42
43namespace android {
44
45// ----------------------------------------------------------------------------
46// Logging support -- this is for debugging only
47// Use "adb shell dumpsys media.camera -v 1" to change it.
48static volatile int32_t gLogLevel = 0;
49
50#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
51#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
52
53static void setLogLevel(int level) {
54    android_atomic_write(level, &gLogLevel);
55}
56
57// ----------------------------------------------------------------------------
58
59static int getCallingPid() {
60    return IPCThreadState::self()->getCallingPid();
61}
62
63static int getCallingUid() {
64    return IPCThreadState::self()->getCallingUid();
65}
66
67// ----------------------------------------------------------------------------
68
69// This is ugly and only safe if we never re-create the CameraService, but
70// should be ok for now.
71static CameraService *gCameraService;
72
73CameraService::CameraService()
74:mSoundRef(0), mModule(0)
75{
76    ALOGI("CameraService started (pid=%d)", getpid());
77    gCameraService = this;
78}
79
80void CameraService::onFirstRef()
81{
82    BnCameraService::onFirstRef();
83
84    if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
85                (const hw_module_t **)&mModule) < 0) {
86        ALOGE("Could not load camera HAL module");
87        mNumberOfCameras = 0;
88    }
89    else {
90        mNumberOfCameras = mModule->get_number_of_cameras();
91        if (mNumberOfCameras > MAX_CAMERAS) {
92            ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
93                    mNumberOfCameras, MAX_CAMERAS);
94            mNumberOfCameras = MAX_CAMERAS;
95        }
96        for (int i = 0; i < mNumberOfCameras; i++) {
97            setCameraFree(i);
98        }
99    }
100}
101
102CameraService::~CameraService() {
103    for (int i = 0; i < mNumberOfCameras; i++) {
104        if (mBusy[i]) {
105            ALOGE("camera %d is still in use in destructor!", i);
106        }
107    }
108
109    gCameraService = NULL;
110}
111
112int32_t CameraService::getNumberOfCameras() {
113    return mNumberOfCameras;
114}
115
116status_t CameraService::getCameraInfo(int cameraId,
117                                      struct CameraInfo* cameraInfo) {
118    if (!mModule) {
119        return NO_INIT;
120    }
121
122    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
123        return BAD_VALUE;
124    }
125
126    struct camera_info info;
127    status_t rc = mModule->get_camera_info(cameraId, &info);
128    cameraInfo->facing = info.facing;
129    cameraInfo->orientation = info.orientation;
130    return rc;
131}
132
133sp<ICamera> CameraService::connect(
134        const sp<ICameraClient>& cameraClient, int cameraId) {
135    int callingPid = getCallingPid();
136    sp<CameraHardwareInterface> hardware = NULL;
137
138    LOG1("CameraService::connect E (pid %d, id %d)", callingPid, cameraId);
139
140    if (!mModule) {
141        ALOGE("Camera HAL module not loaded");
142        return NULL;
143    }
144
145    sp<Client> client;
146    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
147        ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
148            callingPid, cameraId);
149        return NULL;
150    }
151
152    char value[PROPERTY_VALUE_MAX];
153    property_get("sys.secpolicy.camera.disabled", value, "0");
154    if (strcmp(value, "1") == 0) {
155        // Camera is disabled by DevicePolicyManager.
156        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
157        return NULL;
158    }
159
160    Mutex::Autolock lock(mServiceLock);
161    if (mClient[cameraId] != 0) {
162        client = mClient[cameraId].promote();
163        if (client != 0) {
164            if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
165                LOG1("CameraService::connect X (pid %d) (the same client)",
166                     callingPid);
167                return client;
168            } else {
169                ALOGW("CameraService::connect X (pid %d) rejected (existing client).",
170                      callingPid);
171                return NULL;
172            }
173        }
174        mClient[cameraId].clear();
175    }
176
177    if (mBusy[cameraId]) {
178        ALOGW("CameraService::connect X (pid %d) rejected"
179                " (camera %d is still busy).", callingPid, cameraId);
180        return NULL;
181    }
182
183    struct camera_info info;
184    if (mModule->get_camera_info(cameraId, &info) != OK) {
185        ALOGE("Invalid camera id %d", cameraId);
186        return NULL;
187    }
188
189    char camera_device_name[10];
190    snprintf(camera_device_name, sizeof(camera_device_name), "%d", cameraId);
191
192    hardware = new CameraHardwareInterface(camera_device_name);
193    if (hardware->initialize(&mModule->common) != OK) {
194        hardware.clear();
195        return NULL;
196    }
197
198    client = new Client(this, cameraClient, hardware, cameraId, info.facing, callingPid);
199    mClient[cameraId] = client;
200    LOG1("CameraService::connect X (id %d)", cameraId);
201    return client;
202}
203
204void CameraService::removeClient(const sp<ICameraClient>& cameraClient) {
205    int callingPid = getCallingPid();
206    LOG1("CameraService::removeClient E (pid %d)", callingPid);
207
208    for (int i = 0; i < mNumberOfCameras; i++) {
209        // Declare this before the lock to make absolutely sure the
210        // destructor won't be called with the lock held.
211        sp<Client> client;
212
213        Mutex::Autolock lock(mServiceLock);
214
215        // This happens when we have already disconnected (or this is
216        // just another unused camera).
217        if (mClient[i] == 0) continue;
218
219        // Promote mClient. It can fail if we are called from this path:
220        // Client::~Client() -> disconnect() -> removeClient().
221        client = mClient[i].promote();
222
223        if (client == 0) {
224            mClient[i].clear();
225            continue;
226        }
227
228        if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
229            // Found our camera, clear and leave.
230            LOG1("removeClient: clear camera %d", i);
231            mClient[i].clear();
232            break;
233        }
234    }
235
236    LOG1("CameraService::removeClient X (pid %d)", callingPid);
237}
238
239CameraService::Client* CameraService::getClientByIdUnsafe(int cameraId) {
240    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
241    return mClient[cameraId].unsafe_get();
242}
243
244Mutex* CameraService::getClientLockById(int cameraId) {
245    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
246    return &mClientLock[cameraId];
247}
248
249status_t CameraService::onTransact(
250    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
251    // Permission checks
252    switch (code) {
253        case BnCameraService::CONNECT:
254            const int pid = getCallingPid();
255            const int self_pid = getpid();
256            if (pid != self_pid) {
257                // we're called from a different process, do the real check
258                if (!checkCallingPermission(
259                        String16("android.permission.CAMERA"))) {
260                    const int uid = getCallingUid();
261                    ALOGE("Permission Denial: "
262                         "can't use the camera pid=%d, uid=%d", pid, uid);
263                    return PERMISSION_DENIED;
264                }
265            }
266            break;
267    }
268
269    return BnCameraService::onTransact(code, data, reply, flags);
270}
271
272// The reason we need this busy bit is a new CameraService::connect() request
273// may come in while the previous Client's destructor has not been run or is
274// still running. If the last strong reference of the previous Client is gone
275// but the destructor has not been finished, we should not allow the new Client
276// to be created because we need to wait for the previous Client to tear down
277// the hardware first.
278void CameraService::setCameraBusy(int cameraId) {
279    android_atomic_write(1, &mBusy[cameraId]);
280}
281
282void CameraService::setCameraFree(int cameraId) {
283    android_atomic_write(0, &mBusy[cameraId]);
284}
285
286// We share the media players for shutter and recording sound for all clients.
287// A reference count is kept to determine when we will actually release the
288// media players.
289
290MediaPlayer* CameraService::newMediaPlayer(const char *file) {
291    MediaPlayer* mp = new MediaPlayer();
292    if (mp->setDataSource(file, NULL) == NO_ERROR) {
293        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
294        mp->prepare();
295    } else {
296        ALOGE("Failed to load CameraService sounds: %s", file);
297        return NULL;
298    }
299    return mp;
300}
301
302void CameraService::loadSound() {
303    Mutex::Autolock lock(mSoundLock);
304    LOG1("CameraService::loadSound ref=%d", mSoundRef);
305    if (mSoundRef++) return;
306
307    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
308    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
309}
310
311void CameraService::releaseSound() {
312    Mutex::Autolock lock(mSoundLock);
313    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
314    if (--mSoundRef) return;
315
316    for (int i = 0; i < NUM_SOUNDS; i++) {
317        if (mSoundPlayer[i] != 0) {
318            mSoundPlayer[i]->disconnect();
319            mSoundPlayer[i].clear();
320        }
321    }
322}
323
324void CameraService::playSound(sound_kind kind) {
325    LOG1("playSound(%d)", kind);
326    Mutex::Autolock lock(mSoundLock);
327    sp<MediaPlayer> player = mSoundPlayer[kind];
328    if (player != 0) {
329        player->seekTo(0);
330        player->start();
331    }
332}
333
334// ----------------------------------------------------------------------------
335
336CameraService::Client::Client(const sp<CameraService>& cameraService,
337        const sp<ICameraClient>& cameraClient,
338        const sp<CameraHardwareInterface>& hardware,
339        int cameraId, int cameraFacing, int clientPid) {
340    int callingPid = getCallingPid();
341    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
342
343    mCameraService = cameraService;
344    mCameraClient = cameraClient;
345    mHardware = hardware;
346    mCameraId = cameraId;
347    mCameraFacing = cameraFacing;
348    mClientPid = clientPid;
349    mMsgEnabled = 0;
350    mSurface = 0;
351    mPreviewWindow = 0;
352    mDestructionStarted = false;
353    mHardware->setCallbacks(notifyCallback,
354                            dataCallback,
355                            dataCallbackTimestamp,
356                            (void *)cameraId);
357
358    // Enable zoom, error, focus, and metadata messages by default
359    enableMsgType(CAMERA_MSG_ERROR | CAMERA_MSG_ZOOM | CAMERA_MSG_FOCUS |
360                  CAMERA_MSG_PREVIEW_METADATA | CAMERA_MSG_FOCUS_MOVE);
361
362    // Callback is disabled by default
363    mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
364    mOrientation = getOrientation(0, mCameraFacing == CAMERA_FACING_FRONT);
365    mPlayShutterSound = true;
366    cameraService->setCameraBusy(cameraId);
367    cameraService->loadSound();
368    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
369}
370
371// tear down the client
372CameraService::Client::~Client() {
373    // this lock should never be NULL
374    Mutex* lock = mCameraService->getClientLockById(mCameraId);
375    lock->lock();
376    mDestructionStarted = true;
377    // client will not be accessed from callback. should unlock to prevent dead-lock in disconnect
378    lock->unlock();
379    int callingPid = getCallingPid();
380    LOG1("Client::~Client E (pid %d, this %p)", callingPid, this);
381
382    // set mClientPid to let disconnet() tear down the hardware
383    mClientPid = callingPid;
384    disconnect();
385    mCameraService->releaseSound();
386    LOG1("Client::~Client X (pid %d, this %p)", callingPid, this);
387}
388
389// ----------------------------------------------------------------------------
390
391status_t CameraService::Client::checkPid() const {
392    int callingPid = getCallingPid();
393    if (callingPid == mClientPid) return NO_ERROR;
394
395    ALOGW("attempt to use a locked camera from a different process"
396         " (old pid %d, new pid %d)", mClientPid, callingPid);
397    return EBUSY;
398}
399
400status_t CameraService::Client::checkPidAndHardware() const {
401    status_t result = checkPid();
402    if (result != NO_ERROR) return result;
403    if (mHardware == 0) {
404        ALOGE("attempt to use a camera after disconnect() (pid %d)", getCallingPid());
405        return INVALID_OPERATION;
406    }
407    return NO_ERROR;
408}
409
410status_t CameraService::Client::lock() {
411    int callingPid = getCallingPid();
412    LOG1("lock (pid %d)", callingPid);
413    Mutex::Autolock ilock(mICameraLock);
414    Mutex::Autolock lock(mLock);
415
416    // lock camera to this client if the the camera is unlocked
417    if (mClientPid == 0) {
418        mClientPid = callingPid;
419        return NO_ERROR;
420    }
421
422    // returns NO_ERROR if the client already owns the camera, EBUSY otherwise
423    return checkPid();
424}
425
426status_t CameraService::Client::unlock() {
427    int callingPid = getCallingPid();
428    LOG1("unlock (pid %d)", callingPid);
429    Mutex::Autolock iLock(mICameraLock);
430    Mutex::Autolock lock(mLock);
431
432    // allow anyone to use camera (after they lock the camera)
433    status_t result = checkPid();
434    if (result == NO_ERROR) {
435        if (mHardware->recordingEnabled()) {
436            ALOGE("Not allowed to unlock camera during recording.");
437            return INVALID_OPERATION;
438        }
439        mClientPid = 0;
440        LOG1("clear mCameraClient (pid %d)", callingPid);
441        // we need to remove the reference to ICameraClient so that when the app
442        // goes away, the reference count goes to 0.
443        mCameraClient.clear();
444    }
445    return result;
446}
447
448// connect a new client to the camera
449status_t CameraService::Client::connect(const sp<ICameraClient>& client) {
450    int callingPid = getCallingPid();
451    LOG1("connect E (pid %d)", callingPid);
452    Mutex::Autolock iLock(mICameraLock);
453    Mutex::Autolock lock(mLock);
454
455    if (mClientPid != 0 && checkPid() != NO_ERROR) {
456        ALOGW("Tried to connect to a locked camera (old pid %d, new pid %d)",
457                mClientPid, callingPid);
458        return EBUSY;
459    }
460
461    if (mCameraClient != 0 && (client->asBinder() == mCameraClient->asBinder())) {
462        LOG1("Connect to the same client");
463        return NO_ERROR;
464    }
465
466    mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
467    mClientPid = callingPid;
468    mCameraClient = client;
469
470    LOG1("connect X (pid %d)", callingPid);
471    return NO_ERROR;
472}
473
474static void disconnectWindow(const sp<ANativeWindow>& window) {
475    if (window != 0) {
476        status_t result = native_window_api_disconnect(window.get(),
477                NATIVE_WINDOW_API_CAMERA);
478        if (result != NO_ERROR) {
479            ALOGW("native_window_api_disconnect failed: %s (%d)", strerror(-result),
480                    result);
481        }
482    }
483}
484
485void CameraService::Client::disconnect() {
486    int callingPid = getCallingPid();
487    LOG1("disconnect E (pid %d)", callingPid);
488    Mutex::Autolock iLock(mICameraLock);
489    Mutex::Autolock lock(mLock);
490
491    if (checkPid() != NO_ERROR) {
492        ALOGW("different client - don't disconnect");
493        return;
494    }
495
496    if (mClientPid <= 0) {
497        LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid);
498        return;
499    }
500
501    // Make sure disconnect() is done once and once only, whether it is called
502    // from the user directly, or called by the destructor.
503    if (mHardware == 0) return;
504
505    LOG1("hardware teardown");
506    // Before destroying mHardware, we must make sure it's in the
507    // idle state.
508    // Turn off all messages.
509    disableMsgType(CAMERA_MSG_ALL_MSGS);
510    mHardware->stopPreview();
511    mHardware->cancelPicture();
512    // Release the hardware resources.
513    mHardware->release();
514
515    // Release the held ANativeWindow resources.
516    if (mPreviewWindow != 0) {
517        disconnectWindow(mPreviewWindow);
518        mPreviewWindow = 0;
519        mHardware->setPreviewWindow(mPreviewWindow);
520    }
521    mHardware.clear();
522
523    mCameraService->removeClient(mCameraClient);
524    mCameraService->setCameraFree(mCameraId);
525
526    LOG1("disconnect X (pid %d)", callingPid);
527}
528
529// ----------------------------------------------------------------------------
530
531status_t CameraService::Client::setPreviewWindow(const sp<IBinder>& binder,
532        const sp<ANativeWindow>& window) {
533    Mutex::Autolock iLock(mICameraLock);
534    Mutex::Autolock lock(mLock);
535    status_t result = checkPidAndHardware();
536    if (result != NO_ERROR) return result;
537
538    // return if no change in surface.
539    if (binder == mSurface) {
540        return NO_ERROR;
541    }
542
543    if (window != 0) {
544        result = native_window_api_connect(window.get(), NATIVE_WINDOW_API_CAMERA);
545        if (result != NO_ERROR) {
546            ALOGE("native_window_api_connect failed: %s (%d)", strerror(-result),
547                    result);
548            return result;
549        }
550    }
551
552    // If preview has been already started, register preview buffers now.
553    if (mHardware->previewEnabled()) {
554        if (window != 0) {
555            native_window_set_scaling_mode(window.get(),
556                    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
557            native_window_set_buffers_transform(window.get(), mOrientation);
558            result = mHardware->setPreviewWindow(window);
559        }
560    }
561
562    if (result == NO_ERROR) {
563        // Everything has succeeded.  Disconnect the old window and remember the
564        // new window.
565        disconnectWindow(mPreviewWindow);
566        mSurface = binder;
567        mPreviewWindow = window;
568    } else {
569        // Something went wrong after we connected to the new window, so
570        // disconnect here.
571        disconnectWindow(window);
572    }
573
574    return result;
575}
576
577// set the Surface that the preview will use
578status_t CameraService::Client::setPreviewDisplay(const sp<Surface>& surface) {
579    LOG1("setPreviewDisplay(%p) (pid %d)", surface.get(), getCallingPid());
580
581    sp<IBinder> binder(surface != 0 ? surface->asBinder() : 0);
582    sp<ANativeWindow> window(surface);
583    return setPreviewWindow(binder, window);
584}
585
586// set the SurfaceTexture that the preview will use
587status_t CameraService::Client::setPreviewTexture(
588        const sp<ISurfaceTexture>& surfaceTexture) {
589    LOG1("setPreviewTexture(%p) (pid %d)", surfaceTexture.get(),
590            getCallingPid());
591
592    sp<IBinder> binder;
593    sp<ANativeWindow> window;
594    if (surfaceTexture != 0) {
595        binder = surfaceTexture->asBinder();
596        window = new SurfaceTextureClient(surfaceTexture);
597    }
598    return setPreviewWindow(binder, window);
599}
600
601// set the preview callback flag to affect how the received frames from
602// preview are handled.
603void CameraService::Client::setPreviewCallbackFlag(int callback_flag) {
604    LOG1("setPreviewCallbackFlag(%d) (pid %d)", callback_flag, getCallingPid());
605    Mutex::Autolock iLock(mICameraLock);
606    Mutex::Autolock lock(mLock);
607    if (checkPidAndHardware() != NO_ERROR) return;
608
609    mPreviewCallbackFlag = callback_flag;
610    if (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK) {
611        enableMsgType(CAMERA_MSG_PREVIEW_FRAME);
612    } else {
613        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
614    }
615}
616
617// start preview mode
618status_t CameraService::Client::startPreview() {
619    LOG1("startPreview (pid %d)", getCallingPid());
620    return startCameraMode(CAMERA_PREVIEW_MODE);
621}
622
623// start recording mode
624status_t CameraService::Client::startRecording() {
625    LOG1("startRecording (pid %d)", getCallingPid());
626    return startCameraMode(CAMERA_RECORDING_MODE);
627}
628
629// start preview or recording
630status_t CameraService::Client::startCameraMode(camera_mode mode) {
631    LOG1("startCameraMode(%d)", mode);
632    Mutex::Autolock iLock(mICameraLock);
633    Mutex::Autolock lock(mLock);
634    status_t result = checkPidAndHardware();
635    if (result != NO_ERROR) return result;
636
637    switch(mode) {
638        case CAMERA_PREVIEW_MODE:
639            if (mSurface == 0 && mPreviewWindow == 0) {
640                LOG1("mSurface is not set yet.");
641                // still able to start preview in this case.
642            }
643            return startPreviewMode();
644        case CAMERA_RECORDING_MODE:
645            if (mSurface == 0 && mPreviewWindow == 0) {
646                ALOGE("mSurface or mPreviewWindow must be set before startRecordingMode.");
647                return INVALID_OPERATION;
648            }
649            return startRecordingMode();
650        default:
651            return UNKNOWN_ERROR;
652    }
653}
654
655status_t CameraService::Client::startPreviewMode() {
656    LOG1("startPreviewMode");
657    status_t result = NO_ERROR;
658
659    // if preview has been enabled, nothing needs to be done
660    if (mHardware->previewEnabled()) {
661        return NO_ERROR;
662    }
663
664    if (mPreviewWindow != 0) {
665        native_window_set_scaling_mode(mPreviewWindow.get(),
666                NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
667        native_window_set_buffers_transform(mPreviewWindow.get(),
668                mOrientation);
669    }
670    mHardware->setPreviewWindow(mPreviewWindow);
671    result = mHardware->startPreview();
672
673    return result;
674}
675
676status_t CameraService::Client::startRecordingMode() {
677    LOG1("startRecordingMode");
678    status_t result = NO_ERROR;
679
680    // if recording has been enabled, nothing needs to be done
681    if (mHardware->recordingEnabled()) {
682        return NO_ERROR;
683    }
684
685    // if preview has not been started, start preview first
686    if (!mHardware->previewEnabled()) {
687        result = startPreviewMode();
688        if (result != NO_ERROR) {
689            return result;
690        }
691    }
692
693    // start recording mode
694    enableMsgType(CAMERA_MSG_VIDEO_FRAME);
695    mCameraService->playSound(SOUND_RECORDING);
696    result = mHardware->startRecording();
697    if (result != NO_ERROR) {
698        ALOGE("mHardware->startRecording() failed with status %d", result);
699    }
700    return result;
701}
702
703// stop preview mode
704void CameraService::Client::stopPreview() {
705    LOG1("stopPreview (pid %d)", getCallingPid());
706    Mutex::Autolock iLock(mICameraLock);
707    Mutex::Autolock lock(mLock);
708    if (checkPidAndHardware() != NO_ERROR) return;
709
710
711    disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
712    mHardware->stopPreview();
713
714    mPreviewBuffer.clear();
715}
716
717// stop recording mode
718void CameraService::Client::stopRecording() {
719    LOG1("stopRecording (pid %d)", getCallingPid());
720    Mutex::Autolock iLock(mICameraLock);
721    Mutex::Autolock lock(mLock);
722    if (checkPidAndHardware() != NO_ERROR) return;
723
724    mCameraService->playSound(SOUND_RECORDING);
725    disableMsgType(CAMERA_MSG_VIDEO_FRAME);
726    mHardware->stopRecording();
727
728    mPreviewBuffer.clear();
729}
730
731// release a recording frame
732void CameraService::Client::releaseRecordingFrame(const sp<IMemory>& mem) {
733    Mutex::Autolock iLock(mICameraLock);
734    Mutex::Autolock lock(mLock);
735    if (checkPidAndHardware() != NO_ERROR) return;
736    mHardware->releaseRecordingFrame(mem);
737}
738
739status_t CameraService::Client::storeMetaDataInBuffers(bool enabled)
740{
741    LOG1("storeMetaDataInBuffers: %s", enabled? "true": "false");
742    Mutex::Autolock iLock(mICameraLock);
743    Mutex::Autolock lock(mLock);
744    if (checkPidAndHardware() != NO_ERROR) {
745        return UNKNOWN_ERROR;
746    }
747    return mHardware->storeMetaDataInBuffers(enabled);
748}
749
750bool CameraService::Client::previewEnabled() {
751    LOG1("previewEnabled (pid %d)", getCallingPid());
752
753    Mutex::Autolock iLock(mICameraLock);
754    Mutex::Autolock lock(mLock);
755    if (checkPidAndHardware() != NO_ERROR) return false;
756    return mHardware->previewEnabled();
757}
758
759bool CameraService::Client::recordingEnabled() {
760    LOG1("recordingEnabled (pid %d)", getCallingPid());
761
762    Mutex::Autolock iLock(mICameraLock);
763    Mutex::Autolock lock(mLock);
764    if (checkPidAndHardware() != NO_ERROR) return false;
765    return mHardware->recordingEnabled();
766}
767
768status_t CameraService::Client::autoFocus() {
769    LOG1("autoFocus (pid %d)", getCallingPid());
770
771    Mutex::Autolock iLock(mICameraLock);
772    Mutex::Autolock lock(mLock);
773    status_t result = checkPidAndHardware();
774    if (result != NO_ERROR) return result;
775
776    return mHardware->autoFocus();
777}
778
779status_t CameraService::Client::cancelAutoFocus() {
780    LOG1("cancelAutoFocus (pid %d)", getCallingPid());
781
782    Mutex::Autolock iLock(mICameraLock);
783    Mutex::Autolock lock(mLock);
784    status_t result = checkPidAndHardware();
785    if (result != NO_ERROR) return result;
786
787    return mHardware->cancelAutoFocus();
788}
789
790// take a picture - image is returned in callback
791status_t CameraService::Client::takePicture(int msgType) {
792    LOG1("takePicture (pid %d): 0x%x", getCallingPid(), msgType);
793
794    Mutex::Autolock iLock(mICameraLock);
795    int picMsgType = 0;
796    { // scope for lock
797        Mutex::Autolock lock(mLock);
798        status_t result = checkPidAndHardware();
799        if (result != NO_ERROR) return result;
800
801        if ((msgType & CAMERA_MSG_RAW_IMAGE) &&
802                (msgType & CAMERA_MSG_RAW_IMAGE_NOTIFY)) {
803            ALOGE("CAMERA_MSG_RAW_IMAGE and CAMERA_MSG_RAW_IMAGE_NOTIFY"
804                    " cannot be both enabled");
805            return BAD_VALUE;
806        }
807
808        // We only accept picture related message types
809        // and ignore other types of messages for takePicture().
810        picMsgType = msgType
811                & (CAMERA_MSG_SHUTTER |
812                        CAMERA_MSG_POSTVIEW_FRAME |
813                        CAMERA_MSG_RAW_IMAGE |
814                        CAMERA_MSG_RAW_IMAGE_NOTIFY |
815                        CAMERA_MSG_COMPRESSED_IMAGE);
816
817    }
818    enableMsgType(picMsgType);
819
820    return mHardware->takePicture();
821}
822
823// set preview/capture parameters - key/value pairs
824status_t CameraService::Client::setParameters(const String8& params) {
825    LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string());
826
827    Mutex::Autolock iLock(mICameraLock);
828    Mutex::Autolock lock(mLock);
829    status_t result = checkPidAndHardware();
830    if (result != NO_ERROR) return result;
831
832    CameraParameters p(params);
833    return mHardware->setParameters(p);
834}
835
836// get preview/capture parameters - key/value pairs
837String8 CameraService::Client::getParameters() const {
838    Mutex::Autolock iLock(mICameraLock);
839    Mutex::Autolock lock(mLock);
840    if (checkPidAndHardware() != NO_ERROR) return String8();
841
842    String8 params(mHardware->getParameters().flatten());
843    LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string());
844    return params;
845}
846
847// enable shutter sound
848status_t CameraService::Client::enableShutterSound(bool enable) {
849    LOG1("enableShutterSound (pid %d)", getCallingPid());
850
851    status_t result = checkPidAndHardware();
852    if (result != NO_ERROR) return result;
853
854    if (enable) {
855        mPlayShutterSound = true;
856        return OK;
857    }
858
859    // Disabling shutter sound may not be allowed. In that case only
860    // allow the mediaserver process to disable the sound.
861    char value[PROPERTY_VALUE_MAX];
862    property_get("ro.camera.sound.forced", value, "0");
863    if (strcmp(value, "0") != 0) {
864        // Disabling shutter sound is not allowed. Deny if the current
865        // process is not mediaserver.
866        if (getCallingPid() != getpid()) {
867            ALOGE("Failed to disable shutter sound. Permission denied (pid %d)", getCallingPid());
868            return PERMISSION_DENIED;
869        }
870    }
871
872    mPlayShutterSound = false;
873    return OK;
874}
875
876status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
877    LOG1("sendCommand (pid %d)", getCallingPid());
878    int orientation;
879    Mutex::Autolock iLock(mICameraLock);
880    Mutex::Autolock lock(mLock);
881    status_t result = checkPidAndHardware();
882    if (result != NO_ERROR) return result;
883
884    if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) {
885        // Mirror the preview if the camera is front-facing.
886        orientation = getOrientation(arg1, mCameraFacing == CAMERA_FACING_FRONT);
887        if (orientation == -1) return BAD_VALUE;
888
889        if (mOrientation != orientation) {
890            mOrientation = orientation;
891            if (mPreviewWindow != 0) {
892                native_window_set_buffers_transform(mPreviewWindow.get(),
893                        mOrientation);
894            }
895        }
896        return OK;
897    } else if (cmd == CAMERA_CMD_ENABLE_SHUTTER_SOUND) {
898        switch (arg1) {
899            case 0:
900                enableShutterSound(false);
901                break;
902            case 1:
903                enableShutterSound(true);
904                break;
905            default:
906                return BAD_VALUE;
907        }
908        return OK;
909    } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
910        mCameraService->playSound(SOUND_RECORDING);
911    } else if (cmd == CAMERA_CMD_PING) {
912        // If mHardware is 0, checkPidAndHardware will return error.
913        return OK;
914    }
915
916    return mHardware->sendCommand(cmd, arg1, arg2);
917}
918
919// ----------------------------------------------------------------------------
920
921void CameraService::Client::enableMsgType(int32_t msgType) {
922    android_atomic_or(msgType, &mMsgEnabled);
923    mHardware->enableMsgType(msgType);
924}
925
926void CameraService::Client::disableMsgType(int32_t msgType) {
927    android_atomic_and(~msgType, &mMsgEnabled);
928    mHardware->disableMsgType(msgType);
929}
930
931#define CHECK_MESSAGE_INTERVAL 10 // 10ms
932bool CameraService::Client::lockIfMessageWanted(int32_t msgType) {
933    int sleepCount = 0;
934    while (mMsgEnabled & msgType) {
935        if (mLock.tryLock() == NO_ERROR) {
936            if (sleepCount > 0) {
937                LOG1("lockIfMessageWanted(%d): waited for %d ms",
938                    msgType, sleepCount * CHECK_MESSAGE_INTERVAL);
939            }
940            return true;
941        }
942        if (sleepCount++ == 0) {
943            LOG1("lockIfMessageWanted(%d): enter sleep", msgType);
944        }
945        usleep(CHECK_MESSAGE_INTERVAL * 1000);
946    }
947    ALOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType);
948    return false;
949}
950
951// ----------------------------------------------------------------------------
952
953Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
954    return gCameraService->getClientLockById((int) user);
955}
956
957// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
958// be acquired for this to be safe
959CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
960    Client* client = gCameraService->getClientByIdUnsafe((int) user);
961
962    // This could happen if the Client is in the process of shutting down (the
963    // last strong reference is gone, but the destructor hasn't finished
964    // stopping the hardware).
965    if (client == NULL) return NULL;
966
967    // destruction already started, so should not be accessed
968    if (client->mDestructionStarted) return NULL;
969
970    // The checks below are not necessary and are for debugging only.
971    if (client->mCameraService.get() != gCameraService) {
972        ALOGE("mismatch service!");
973        return NULL;
974    }
975
976    if (client->mHardware == 0) {
977        ALOGE("mHardware == 0: callback after disconnect()?");
978        return NULL;
979    }
980
981    return client;
982}
983
984// Callback messages can be dispatched to internal handlers or pass to our
985// client's callback functions, depending on the message type.
986//
987// notifyCallback:
988//      CAMERA_MSG_SHUTTER              handleShutter
989//      (others)                        c->notifyCallback
990// dataCallback:
991//      CAMERA_MSG_PREVIEW_FRAME        handlePreviewData
992//      CAMERA_MSG_POSTVIEW_FRAME       handlePostview
993//      CAMERA_MSG_RAW_IMAGE            handleRawPicture
994//      CAMERA_MSG_COMPRESSED_IMAGE     handleCompressedPicture
995//      (others)                        c->dataCallback
996// dataCallbackTimestamp
997//      (others)                        c->dataCallbackTimestamp
998//
999// NOTE: the *Callback functions grab mLock of the client before passing
1000// control to handle* functions. So the handle* functions must release the
1001// lock before calling the ICameraClient's callbacks, so those callbacks can
1002// invoke methods in the Client class again (For example, the preview frame
1003// callback may want to releaseRecordingFrame). The handle* functions must
1004// release the lock after all accesses to member variables, so it must be
1005// handled very carefully.
1006
1007void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1,
1008        int32_t ext2, void* user) {
1009    LOG2("notifyCallback(%d)", msgType);
1010
1011    Mutex* lock = getClientLockFromCookie(user);
1012    if (lock == NULL) return;
1013    Mutex::Autolock alock(*lock);
1014
1015    Client* client = getClientFromCookie(user);
1016    if (client == NULL) return;
1017
1018    if (!client->lockIfMessageWanted(msgType)) return;
1019
1020    switch (msgType) {
1021        case CAMERA_MSG_SHUTTER:
1022            // ext1 is the dimension of the yuv picture.
1023            client->handleShutter();
1024            break;
1025        default:
1026            client->handleGenericNotify(msgType, ext1, ext2);
1027            break;
1028    }
1029}
1030
1031void CameraService::Client::dataCallback(int32_t msgType,
1032        const sp<IMemory>& dataPtr, camera_frame_metadata_t *metadata, void* user) {
1033    LOG2("dataCallback(%d)", msgType);
1034
1035    Mutex* lock = getClientLockFromCookie(user);
1036    if (lock == NULL) return;
1037    Mutex::Autolock alock(*lock);
1038
1039    Client* client = getClientFromCookie(user);
1040    if (client == NULL) return;
1041
1042    if (!client->lockIfMessageWanted(msgType)) return;
1043    if (dataPtr == 0 && metadata == NULL) {
1044        ALOGE("Null data returned in data callback");
1045        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
1046        return;
1047    }
1048
1049    switch (msgType & ~CAMERA_MSG_PREVIEW_METADATA) {
1050        case CAMERA_MSG_PREVIEW_FRAME:
1051            client->handlePreviewData(msgType, dataPtr, metadata);
1052            break;
1053        case CAMERA_MSG_POSTVIEW_FRAME:
1054            client->handlePostview(dataPtr);
1055            break;
1056        case CAMERA_MSG_RAW_IMAGE:
1057            client->handleRawPicture(dataPtr);
1058            break;
1059        case CAMERA_MSG_COMPRESSED_IMAGE:
1060            client->handleCompressedPicture(dataPtr);
1061            break;
1062        default:
1063            client->handleGenericData(msgType, dataPtr, metadata);
1064            break;
1065    }
1066}
1067
1068void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp,
1069        int32_t msgType, const sp<IMemory>& dataPtr, void* user) {
1070    LOG2("dataCallbackTimestamp(%d)", msgType);
1071
1072    Mutex* lock = getClientLockFromCookie(user);
1073    if (lock == NULL) return;
1074    Mutex::Autolock alock(*lock);
1075
1076    Client* client = getClientFromCookie(user);
1077    if (client == NULL) return;
1078
1079    if (!client->lockIfMessageWanted(msgType)) return;
1080
1081    if (dataPtr == 0) {
1082        ALOGE("Null data returned in data with timestamp callback");
1083        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
1084        return;
1085    }
1086
1087    client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
1088}
1089
1090// snapshot taken callback
1091void CameraService::Client::handleShutter(void) {
1092    if (mPlayShutterSound) {
1093        mCameraService->playSound(SOUND_SHUTTER);
1094    }
1095
1096    sp<ICameraClient> c = mCameraClient;
1097    if (c != 0) {
1098        mLock.unlock();
1099        c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
1100        if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
1101    }
1102    disableMsgType(CAMERA_MSG_SHUTTER);
1103
1104    mLock.unlock();
1105}
1106
1107// preview callback - frame buffer update
1108void CameraService::Client::handlePreviewData(int32_t msgType,
1109                                              const sp<IMemory>& mem,
1110                                              camera_frame_metadata_t *metadata) {
1111    ssize_t offset;
1112    size_t size;
1113    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1114
1115    // local copy of the callback flags
1116    int flags = mPreviewCallbackFlag;
1117
1118    // is callback enabled?
1119    if (!(flags & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
1120        // If the enable bit is off, the copy-out and one-shot bits are ignored
1121        LOG2("frame callback is disabled");
1122        mLock.unlock();
1123        return;
1124    }
1125
1126    // hold a strong pointer to the client
1127    sp<ICameraClient> c = mCameraClient;
1128
1129    // clear callback flags if no client or one-shot mode
1130    if (c == 0 || (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
1131        LOG2("Disable preview callback");
1132        mPreviewCallbackFlag &= ~(CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
1133                                  CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
1134                                  CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK);
1135        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
1136    }
1137
1138    if (c != 0) {
1139        // Is the received frame copied out or not?
1140        if (flags & CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
1141            LOG2("frame is copied");
1142            copyFrameAndPostCopiedFrame(msgType, c, heap, offset, size, metadata);
1143        } else {
1144            LOG2("frame is forwarded");
1145            mLock.unlock();
1146            c->dataCallback(msgType, mem, metadata);
1147        }
1148    } else {
1149        mLock.unlock();
1150    }
1151}
1152
1153// picture callback - postview image ready
1154void CameraService::Client::handlePostview(const sp<IMemory>& mem) {
1155    disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);
1156
1157    sp<ICameraClient> c = mCameraClient;
1158    mLock.unlock();
1159    if (c != 0) {
1160        c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem, NULL);
1161    }
1162}
1163
1164// picture callback - raw image ready
1165void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) {
1166    disableMsgType(CAMERA_MSG_RAW_IMAGE);
1167
1168    ssize_t offset;
1169    size_t size;
1170    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1171
1172    sp<ICameraClient> c = mCameraClient;
1173    mLock.unlock();
1174    if (c != 0) {
1175        c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem, NULL);
1176    }
1177}
1178
1179// picture callback - compressed picture ready
1180void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) {
1181    disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
1182
1183    sp<ICameraClient> c = mCameraClient;
1184    mLock.unlock();
1185    if (c != 0) {
1186        c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem, NULL);
1187    }
1188}
1189
1190
1191void CameraService::Client::handleGenericNotify(int32_t msgType,
1192    int32_t ext1, int32_t ext2) {
1193    sp<ICameraClient> c = mCameraClient;
1194    mLock.unlock();
1195    if (c != 0) {
1196        c->notifyCallback(msgType, ext1, ext2);
1197    }
1198}
1199
1200void CameraService::Client::handleGenericData(int32_t msgType,
1201    const sp<IMemory>& dataPtr, camera_frame_metadata_t *metadata) {
1202    sp<ICameraClient> c = mCameraClient;
1203    mLock.unlock();
1204    if (c != 0) {
1205        c->dataCallback(msgType, dataPtr, metadata);
1206    }
1207}
1208
1209void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp,
1210    int32_t msgType, const sp<IMemory>& dataPtr) {
1211    sp<ICameraClient> c = mCameraClient;
1212    mLock.unlock();
1213    if (c != 0) {
1214        c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
1215    }
1216}
1217
1218void CameraService::Client::copyFrameAndPostCopiedFrame(
1219        int32_t msgType, const sp<ICameraClient>& client,
1220        const sp<IMemoryHeap>& heap, size_t offset, size_t size,
1221        camera_frame_metadata_t *metadata) {
1222    LOG2("copyFrameAndPostCopiedFrame");
1223    // It is necessary to copy out of pmem before sending this to
1224    // the callback. For efficiency, reuse the same MemoryHeapBase
1225    // provided it's big enough. Don't allocate the memory or
1226    // perform the copy if there's no callback.
1227    // hold the preview lock while we grab a reference to the preview buffer
1228    sp<MemoryHeapBase> previewBuffer;
1229
1230    if (mPreviewBuffer == 0) {
1231        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1232    } else if (size > mPreviewBuffer->virtualSize()) {
1233        mPreviewBuffer.clear();
1234        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1235    }
1236    if (mPreviewBuffer == 0) {
1237        ALOGE("failed to allocate space for preview buffer");
1238        mLock.unlock();
1239        return;
1240    }
1241    previewBuffer = mPreviewBuffer;
1242
1243    memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);
1244
1245    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
1246    if (frame == 0) {
1247        ALOGE("failed to allocate space for frame callback");
1248        mLock.unlock();
1249        return;
1250    }
1251
1252    mLock.unlock();
1253    client->dataCallback(msgType, frame, metadata);
1254}
1255
1256int CameraService::Client::getOrientation(int degrees, bool mirror) {
1257    if (!mirror) {
1258        if (degrees == 0) return 0;
1259        else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
1260        else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
1261        else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
1262    } else {  // Do mirror (horizontal flip)
1263        if (degrees == 0) {           // FLIP_H and ROT_0
1264            return HAL_TRANSFORM_FLIP_H;
1265        } else if (degrees == 90) {   // FLIP_H and ROT_90
1266            return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
1267        } else if (degrees == 180) {  // FLIP_H and ROT_180
1268            return HAL_TRANSFORM_FLIP_V;
1269        } else if (degrees == 270) {  // FLIP_H and ROT_270
1270            return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
1271        }
1272    }
1273    ALOGE("Invalid setDisplayOrientation degrees=%d", degrees);
1274    return -1;
1275}
1276
1277// ----------------------------------------------------------------------------
1278
1279static const int kDumpLockRetries = 50;
1280static const int kDumpLockSleep = 60000;
1281
1282static bool tryLock(Mutex& mutex)
1283{
1284    bool locked = false;
1285    for (int i = 0; i < kDumpLockRetries; ++i) {
1286        if (mutex.tryLock() == NO_ERROR) {
1287            locked = true;
1288            break;
1289        }
1290        usleep(kDumpLockSleep);
1291    }
1292    return locked;
1293}
1294
1295status_t CameraService::dump(int fd, const Vector<String16>& args) {
1296    static const char* kDeadlockedString = "CameraService may be deadlocked\n";
1297
1298    const size_t SIZE = 256;
1299    char buffer[SIZE];
1300    String8 result;
1301    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1302        snprintf(buffer, SIZE, "Permission Denial: "
1303                "can't dump CameraService from pid=%d, uid=%d\n",
1304                getCallingPid(),
1305                getCallingUid());
1306        result.append(buffer);
1307        write(fd, result.string(), result.size());
1308    } else {
1309        bool locked = tryLock(mServiceLock);
1310        // failed to lock - CameraService is probably deadlocked
1311        if (!locked) {
1312            String8 result(kDeadlockedString);
1313            write(fd, result.string(), result.size());
1314        }
1315
1316        bool hasClient = false;
1317        for (int i = 0; i < mNumberOfCameras; i++) {
1318            sp<Client> client = mClient[i].promote();
1319            if (client == 0) continue;
1320            hasClient = true;
1321            sprintf(buffer, "Client[%d] (%p) PID: %d\n",
1322                    i,
1323                    client->getCameraClient()->asBinder().get(),
1324                    client->mClientPid);
1325            result.append(buffer);
1326            write(fd, result.string(), result.size());
1327            client->mHardware->dump(fd, args);
1328        }
1329        if (!hasClient) {
1330            result.append("No camera client yet.\n");
1331            write(fd, result.string(), result.size());
1332        }
1333
1334        if (locked) mServiceLock.unlock();
1335
1336        // change logging level
1337        int n = args.size();
1338        for (int i = 0; i + 1 < n; i++) {
1339            if (args[i] == String16("-v")) {
1340                String8 levelStr(args[i+1]);
1341                int level = atoi(levelStr.string());
1342                sprintf(buffer, "Set Log Level to %d", level);
1343                result.append(buffer);
1344                setLogLevel(level);
1345            }
1346        }
1347    }
1348    return NO_ERROR;
1349}
1350
1351}; // namespace android
1352