• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import fileio from '@ohos.fileio'
17import mediaLibrary from '@ohos.multimedia.mediaLibrary'
18
19import { Log } from '../utils/Log'
20import DateTimeUtil from '../utils/DateTimeUtil'
21import { FunctionCallBack, VideoCallBack } from './CameraService'
22import ThumbnailGetter from './ThumbnailGetter'
23import Trace from '../utils/Trace'
24
25let photoUri: string;
26
27export default class SaveCameraAsset {
28  constructor() {
29
30  }
31
32  private TAG = '[SaveCameraAsset:] '
33  private lastSaveTime = ''
34  private saveIndex = 0
35  public videoPrepareFile: any
36
37  public getPhotoUri() {
38    Log.log(`${this.TAG} getPhotoUri= ${photoUri}`)
39    return photoUri
40  }
41
42  public saveImage(mReceiver, thumbWidth: number, thumbHeight: number, thumbnailGetter: ThumbnailGetter, captureCallBack: FunctionCallBack) {
43    Log.info(`${this.TAG} saveImage E`)
44    const mDateTimeUtil = new DateTimeUtil();
45    const fileKeyObj = mediaLibrary.FileKey
46    const mediaType = mediaLibrary.MediaType.IMAGE;
47    let buffer = new ArrayBuffer(4096)
48    const media = mediaLibrary.getMediaLibrary(globalThis.cameraAbilityContext);
49    Log.info(`${this.TAG} saveImage mediaLibrary.getMediaLibrary media: ${media}`)
50
51    mReceiver.on('imageArrival', async () => {
52      Trace.start(Trace.UPDATE_PHOTO_THUMBNAIL)
53      Log.log(`${this.TAG} saveImage ImageReceiver on called`)
54      const displayName = this.checkName(`IMG_${mDateTimeUtil.getDate()}_${mDateTimeUtil.getTime()}`) + '.jpg'
55      Log.log(`${this.TAG} saveImage displayName== ${displayName}`)
56      mReceiver.readNextImage((err, image) => {
57        Log.error(`${this.TAG} readNextImage image = ${image} error = ${err}`)
58        if (image === undefined) {
59          Log.info(`${this.TAG} saveImage failed to get valid image`)
60          return
61        }
62        image.getComponent(4, async (errMsg, img) => {
63          Log.info(`${this.TAG} getComponent img = ${img} errMsg = ${errMsg} E`)
64          if (img === undefined) {
65            Log.error(`${this.TAG} getComponent failed to get valid buffer`)
66            return
67          }
68          if (img.byteBuffer) {
69            Log.info(`${this.TAG} getComponent img.byteBuffer = ${img.byteBuffer}`)
70            buffer = img.byteBuffer
71            captureCallBack.onCapturePhotoOutput()
72          } else {
73            Log.info(`${this.TAG} getComponent img.byteBuffer is undefined`)
74          }
75          await image.release()
76          Log.info(`${this.TAG} getComponent  X`)
77        })
78      })
79
80      Log.info(`${this.TAG} saveImage getPublicDirectory `)
81      let publicPath: string = await media.getPublicDirectory(mediaLibrary.DirectoryType.DIR_CAMERA)
82//      publicPath = `${publicPath}Camera/`
83      Log.info(`${this.TAG} saveImage publicPath = ${publicPath}`)
84      const dataUri = await media.createAsset(mediaType, displayName, publicPath)
85      photoUri = dataUri.uri
86      Log.info(`${this.TAG} saveImage photoUri: ${photoUri}`)
87
88      if (dataUri !== undefined) {
89        const args = dataUri.id.toString()
90        const fetchOp = {
91          selections: `${fileKeyObj.ID} = ? `,
92          selectionArgs: [args],
93        }
94        // 通过id去查找
95        Log.log(`${this.TAG} saveImage fetchOp${JSON.stringify(fetchOp)}`)
96        const fetchFileResult = await media.getFileAssets(fetchOp);
97        const fileAsset = await fetchFileResult.getAllObject();
98        if (fileAsset != undefined) {
99          Log.info(`${this.TAG} saveImage fileAsset is not undefined`)
100          fileAsset.forEach((dataInfo) => {
101            Log.info(`${this.TAG} saveImage fileAsset.forEach called`)
102            dataInfo.open('Rw').then((fd) => { // RW是读写方式打开文件 获取fd
103              Log.info(`${this.TAG} saveImage dataInfo.open called`)
104              fileio.write(fd, buffer).then(() => {
105                Log.info(`${this.TAG} saveImage fileio.write called`)
106                dataInfo.close(fd).then(() => {
107                  Log.info(`${this.TAG} saveImage ataInfo.close called`)
108                  thumbnailGetter.getThumbnailInfo(thumbWidth, thumbHeight, photoUri).then(thumbnail => {
109                    Log.info(`${this.TAG} saveImage thumbnailInfo: ${thumbnail}`)
110                    captureCallBack.onCaptureSuccess(thumbnail, photoUri)
111                    Trace.end(Trace.UPDATE_PHOTO_THUMBNAIL)
112                  })
113                  Log.info(`${this.TAG} ==========================fileAsset.close success=======================>`);
114                }).catch(error => {
115                  Trace.write(Trace.SAVE_FAIL)
116                  Log.error(`${this.TAG} saveImage close is error ${JSON.stringify(error)}`)
117                })
118              })
119            })
120          });
121        }
122      } else {
123        Log.error(`${this.TAG} dataUri is null`)
124      }
125    })
126    Log.info(`${this.TAG} saveImage X`)
127  }
128
129  public async createVideoFd(captureCallBack: VideoCallBack): Promise<number> {
130    Log.info(`${this.TAG} getVideoFd E`)
131    const mDateTimeUtil = new DateTimeUtil();
132    const displayName = this.checkName(`VID_${mDateTimeUtil.getDate()}_${mDateTimeUtil.getTime()}`) + '.mp4'
133    const media = mediaLibrary.getMediaLibrary(globalThis.cameraAbilityContext);
134    Log.info(`${this.TAG} getVideoFd publicPath: ${media}`)
135    const fileKeyObj = mediaLibrary.FileKey;
136    const mediaType = mediaLibrary.MediaType.VIDEO;
137    let publicPath: string = await media.getPublicDirectory(mediaLibrary.DirectoryType.DIR_CAMERA)
138    Log.info(`${this.TAG} getVideoFd publicPath: ${JSON.stringify(publicPath)}`)
139//    publicPath = `${publicPath}Camera/`
140    try {
141      const dataUri = await media.createAsset(mediaType, displayName, publicPath)
142      if (dataUri !== undefined) {
143        const args = dataUri.id.toString()
144        const fetchOp = {
145          selections: `${fileKeyObj.ID} = ? `,
146          selectionArgs: [args],
147        }
148        // 通过id去查找
149        Log.log(`${this.TAG} fetchOp= ${JSON.stringify(fetchOp)}`)
150        const fetchFileResult = await media.getFileAssets(fetchOp);
151        Log.info(`${this.TAG} SaveCameraAsset getFileAssets finished`)
152        this.videoPrepareFile = await fetchFileResult.getFirstObject();
153        const getLastObject = await fetchFileResult.getLastObject()
154        captureCallBack.videoUri(getLastObject.uri)
155        Log.info(`${this.TAG} SaveCameraAsset getLastObject.uri: ${JSON.stringify(getLastObject.uri)}`)
156        const fdNumber = await this.videoPrepareFile.open('Rw')
157        return fdNumber;
158      }
159    } catch (err) {
160      Log.error(`${this.TAG} createVideoFd err: ` + err)
161    }
162    Log.info(`${this.TAG} getVideoFd X`)
163  }
164
165  private checkName(name: string): string {
166    if (this.lastSaveTime == name) {
167      this.saveIndex++
168      return `${name}_${this.saveIndex}`
169    }
170    this.lastSaveTime = name
171    this.saveIndex = 0
172    return name
173  }
174}