1 /* 2 * Copyright (C) 2016 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17 package com.googlecode.android_scripting.webcam; 18 19 import java.io.BufferedReader; 20 import java.io.OutputStream; 21 import java.io.PrintWriter; 22 import java.net.Socket; 23 import com.googlecode.android_scripting.Log; 24 import com.googlecode.android_scripting.SimpleServer; 25 26 class MjpegServer extends SimpleServer { 27 28 private final JpegProvider mProvider; 29 MjpegServer(JpegProvider provider)30 public MjpegServer(JpegProvider provider) { 31 mProvider = provider; 32 } 33 34 @Override handleConnection(Socket socket)35 protected void handleConnection(Socket socket) throws Exception { 36 Log.d("handle Mjpeg connection"); 37 byte[] data = mProvider.getJpeg(); 38 if (data == null) { 39 return; 40 } 41 OutputStream outputStream = socket.getOutputStream(); 42 outputStream.write(( 43 "HTTP/1.0 200 OK\r\n" + 44 "Server: SL4A\r\n" + 45 "Connection: close\r\n" + 46 "Max-Age: 0\r\n" + 47 "Expires: 0\r\n" + 48 "Cache-Control: no-cache, private\r\n" + 49 "Pragma: no-cache\r\n" + 50 "Content-Type: multipart/x-mixed-replace; boundary=--BoundaryString\r\n\r\n").getBytes()); 51 while (true) { 52 data = mProvider.getJpeg(); 53 if (data == null) { 54 return; 55 } 56 outputStream.write("--BoundaryString\r\n".getBytes()); 57 outputStream.write("Content-type: image/jpg\r\n".getBytes()); 58 outputStream.write(("Content-Length: " + data.length + "\r\n\r\n").getBytes()); 59 outputStream.write(data); 60 outputStream.write("\r\n\r\n".getBytes()); 61 outputStream.flush(); 62 } 63 } 64 65 @Override handleRPCConnection(Socket sock, Integer UID, BufferedReader reader, PrintWriter writer)66 protected void handleRPCConnection(Socket sock, Integer UID, BufferedReader reader, PrintWriter writer) 67 throws Exception { 68 } 69 } 70