1/* 2 * Copyright (C) 2011 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 18package android.filterpacks.base; 19 20import android.filterfw.core.Filter; 21import android.filterfw.core.FilterContext; 22import android.filterfw.core.Frame; 23import android.filterfw.core.FrameFormat; 24import android.filterfw.core.GenerateFieldPort; 25import android.filterfw.core.GenerateFinalPort; 26import android.filterfw.core.KeyValueMap; 27import android.filterfw.core.MutableFrameFormat; 28import android.filterfw.format.PrimitiveFormat; 29 30import java.io.ByteArrayOutputStream; 31import java.io.InputStream; 32import java.io.IOException; 33import java.nio.ByteBuffer; 34 35/** 36 * @hide 37 */ 38public class InputStreamSource extends Filter { 39 40 @GenerateFinalPort(name = "target") 41 private String mTarget; 42 43 @GenerateFieldPort(name = "stream") 44 private InputStream mInputStream; 45 46 @GenerateFinalPort(name = "format", hasDefault = true) 47 private MutableFrameFormat mOutputFormat = null; 48 49 public InputStreamSource(String name) { 50 super(name); 51 } 52 53 @Override 54 public void setupPorts() { 55 int target = FrameFormat.readTargetString(mTarget); 56 if (mOutputFormat == null) { 57 mOutputFormat = PrimitiveFormat.createByteFormat(target); 58 } 59 addOutputPort("data", mOutputFormat); 60 } 61 62 @Override 63 public void process(FilterContext context) { 64 int fileSize = 0; 65 ByteBuffer byteBuffer = null; 66 67 // Read the file 68 try { 69 ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 70 byte[] buffer = new byte[1024]; 71 int bytesRead; 72 while ((bytesRead = mInputStream.read(buffer)) > 0) { 73 byteStream.write(buffer, 0, bytesRead); 74 fileSize += bytesRead; 75 } 76 byteBuffer = ByteBuffer.wrap(byteStream.toByteArray()); 77 } catch (IOException exception) { 78 throw new RuntimeException( 79 "InputStreamSource: Could not read stream: " + exception.getMessage() + "!"); 80 } 81 82 // Put it into a frame 83 mOutputFormat.setDimensions(fileSize); 84 Frame output = context.getFrameManager().newFrame(mOutputFormat); 85 output.setData(byteBuffer); 86 87 // Push output 88 pushOutput("data", output); 89 90 // Release pushed frame 91 output.release(); 92 93 // Close output port as we are done here 94 closeOutputPort("data"); 95 } 96} 97