/Users/lyon/j4p/src/video/BroadcastMain.java
|
1 package video;
2
3 import gui.In;
4 import j2d.ImageUtils;
5 import net.multicast.McastUtil;
6 import net.multicast.Utils;
7
8 import java.awt.AWTException;
9 import java.awt.Rectangle;
10 import java.io.IOException;
11 import java.net.DatagramPacket;
12 import java.net.InetAddress;
13 import java.net.MulticastSocket;
14
15 /**
16 * Copyright DocJava, inc. User: lyon
17 * <p/>
18 * Date: Nov 25, 2004
19 * <p/>
20 * Time: 6:24:58 AM
21 */
22 public class BroadcastMain {
23 private int port = 2435;
24 private McastUtil mcu = new McastUtil(port);
25
26 public static void main(String[] args) {
27 BroadcastMain bc = new BroadcastMain();
28 }
29
30 public BroadcastMain() {
31 mcu.setLoopBack(true);
32 try {
33 new BroadcastViewerThread(mcu);
34 if (In.getBoolean("do you want to broadcast?"))
35 transmitData();
36 } catch (Exception err) {
37 err.printStackTrace();
38 }
39 }
40
41 private void transmitData() throws IOException, AWTException, InterruptedException {
42 Rectangle rect = In.getRectangle("select a region to capture");
43 for (; ;) {
44 final long now = System.currentTimeMillis();
45 byte b[] = ImageUtils.grabAPngImage(rect);
46 mcu.sendBytes(b);
47 long delta = System.currentTimeMillis() - now;
48 final long minTime = 250;
49 if (delta < minTime)
50 Thread.sleep(minTime - delta);
51 }
52 }
53
54 public void broadcastImages() {
55 try {
56 broadcastImages(In.getInt("select the number " +
57 "of images to capture"));
58 } catch (IOException e) {
59 e.printStackTrace();
60 }
61 }
62
63 /**
64 * broadcast png images using udp multicast packets.
65 *
66 * @param n number of images to send.
67 * @throws java.io.IOException
68 */
69 public void broadcastImages(int n) throws IOException {
70 final InetAddress inetAddress = Utils.getInetAddress();
71 final int port = 1234;
72 final Rectangle rect = In.getRectangle("select a capture area");
73 final MulticastSocket mcastSocket =
74 Utils.getMulticastSocket(port, inetAddress);
75 for (int i = 0; i < n; i++) {
76 try {
77 sendAnImage(mcastSocket, port, inetAddress, rect, i);
78 sleep(1000);
79 } catch (IOException e) {
80 e.printStackTrace();
81 } catch (AWTException e) {
82 e.printStackTrace();
83 }
84 }
85 Utils.closeSocket(mcastSocket, inetAddress);
86 System.out.println("done xmitting");
87 }
88
89 private static void sleep(long i) {
90 try {
91 Thread.sleep(i);
92 } catch (InterruptedException e) {
93 e.printStackTrace();
94 }
95 }
96
97 private void sendAnImage(MulticastSocket mcastSocket, int port,
98 InetAddress inetAddress,
99 Rectangle rect, int i)
100 throws IOException, AWTException {
101 byte b[] = ImageUtils.grabAPngImage(rect);
102 DatagramPacket dp = new DatagramPacket(b,
103 b.length,
104 inetAddress,
105 port);
106 mcastSocket.send(dp);
107 System.out.println("sent image:" + i);
108 }
109 }
110