1 /* 2 * Copyright (C) 2017 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 package com.android.voicemail.impl.transcribe; 17 18 import android.annotation.TargetApi; 19 import android.content.Context; 20 import android.net.Uri; 21 import android.os.Build.VERSION_CODES; 22 import android.support.annotation.Nullable; 23 import android.util.Base64; 24 import com.android.dialer.common.Assert; 25 import com.google.internal.communications.voicemailtranscription.v1.AudioFormat; 26 import com.google.protobuf.ByteString; 27 import java.io.IOException; 28 import java.io.InputStream; 29 import java.security.MessageDigest; 30 import java.security.NoSuchAlgorithmException; 31 32 /** Utility methods used by this transcription package. */ 33 public class TranscriptionUtils { 34 static final String AMR_PREFIX = "#!AMR\n"; 35 getAudioData(Context context, Uri voicemailUri)36 static ByteString getAudioData(Context context, Uri voicemailUri) { 37 try (InputStream in = context.getContentResolver().openInputStream(voicemailUri)) { 38 return ByteString.readFrom(in); 39 } catch (IOException e) { 40 return null; 41 } 42 } 43 getAudioFormat(ByteString audioData)44 static AudioFormat getAudioFormat(ByteString audioData) { 45 return audioData != null && audioData.startsWith(ByteString.copyFromUtf8(AMR_PREFIX)) 46 ? AudioFormat.AMR_NB_8KHZ 47 : AudioFormat.AUDIO_FORMAT_UNSPECIFIED; 48 } 49 50 @TargetApi(VERSION_CODES.O) getFingerprintFor(ByteString data, @Nullable String salt)51 static String getFingerprintFor(ByteString data, @Nullable String salt) { 52 Assert.checkArgument(data != null); 53 try { 54 MessageDigest md = MessageDigest.getInstance("MD5"); 55 if (salt != null) { 56 md.update(salt.getBytes()); 57 } 58 byte[] md5Bytes = md.digest(data.toByteArray()); 59 return Base64.encodeToString(md5Bytes, Base64.DEFAULT); 60 } catch (NoSuchAlgorithmException e) { 61 Assert.fail(e.toString()); 62 } 63 return null; 64 } 65 } 66