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