public void startProcessing() { try { processor = Manager.createProcessor(getMainCamSource()); } catch (IOException e) { // JOptionPane.showMessageDialog(parent, // "IO Exception creating processor: " + e.getMessage(), "Error", // JOptionPane.WARNING_MESSAGE); return; } catch (NoProcessorException e) { // JOptionPane.showMessageDialog(parent, // "Exception creating processor: " + e.getMessage(), "Error", // JOptionPane.WARNING_MESSAGE); return; } CamStateHelper playhelper = new CamStateHelper(processor); if (!playhelper.configure(10000)) { JOptionPane.showMessageDialog( parent, "cannot configure processor", "Error", JOptionPane.WARNING_MESSAGE); return; } processor.setContentDescriptor(null); if (!playhelper.realize(10000)) { JOptionPane.showMessageDialog( parent, "cannot realize processor", "Error", JOptionPane.WARNING_MESSAGE); return; } // In order for or your clones to start, you must start the original source processor.start(); setProcessing(true); }
/** * Initializes the decoder. The file will be opened, decoding will start, and the first frame of * the movie will be sent to the handlers. * * @param mediaFile - the URL of the media file to be loaded */ public void init(String mediaFile) { try { java.net.URL url = new java.net.URL(mediaFile); processor = Manager.createProcessor(url); processor.addControllerListener(this); processor.configure(); } catch (Exception e) { // Debug.trace("Movie player exception "+e); } }
/** * Creates a video stream of the interactions with the given component at the specified frame rate * and saves it as the given file. */ public static Processor recordVideo(Component component, int fps, File dest) { if (component == null) return null; Dimension size = component.getSize(); Point location = component.getLocationOnScreen(); String loc = MessageFormat.format( "screen://{0},{1},{2},{3}/{4}", new Object[] { new Integer(location.x), new Integer(location.y), new Integer(size.width - size.width % 8), new Integer(size.height - size.height % 8), new Integer(fps) }); MediaLocator mSource = new MediaLocator(loc); Processor p = null; try { DataSource data = Manager.createDataSource(mSource); p = Manager.createProcessor(mSource); waitForState(p, Processor.Configured); p.setContentDescriptor(new FileTypeDescriptor("video.x_msvideo")); p.getTrackControls()[0].setFormat(new VideoFormat(VideoFormat.MJPG)); waitForState(p, Processor.Realized); DataSource data2 = p.getDataOutput(); String path = dest.getParent(); String name = dest.getName(); if (!name.toLowerCase().endsWith(".avi")) name += ".avi"; MediaLocator mediaDest = new MediaLocator(new File(path, name).toURL()); DataSink dataSink = Manager.createDataSink(data2, mediaDest); dataSink.open(); dataSink.start(); p.start(); } catch (Exception ex) { ex.printStackTrace(); p = null; } return p; }
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: rtpaudio <targetIP> <targetPort>"); System.exit(0); } try { RegistryDefaults.setDefaultFlags(RegistryDefaults.FMJ); // create a clean registry RegistryDefaults.unRegisterAll(RegistryDefaults.ALL); RegistryDefaults.registerAll(RegistryDefaults.FMJ); // remove all capture devices Vector deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone(); for (int i = 0; i < deviceList.size(); i++) { CaptureDeviceInfo cdi = (CaptureDeviceInfo) deviceList.elementAt(i); CaptureDeviceManager.removeDevice(cdi); } // update capture device list new net.sf.fmj.media.cdp.javasound.CaptureDevicePlugger().addCaptureDevices(); PlugInManager.commit(); deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone(); if ((null == deviceList) || (deviceList.size() == 0)) { System.out.println("### ERROR found no audio capture device"); System.exit(0); } // enumerate all codec Vector codecList = PlugInManager.getPlugInList(null, null, PlugInManager.CODEC); System.out.println("found " + codecList.size() + " codec"); for (int i = 0; i < codecList.size(); i++) { String aCodecClass = (String) codecList.elementAt(i); System.out.println("# " + (i + 1) + " " + aCodecClass); } // fetch first available audio capture device deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone(); CaptureDeviceInfo captureDeviceInfo = (CaptureDeviceInfo) deviceList.elementAt(0); System.out.println("### using " + captureDeviceInfo.getName()); System.out.println("### locator " + captureDeviceInfo.getLocator()); javax.media.protocol.DataSource dataSource = javax.media.Manager.createDataSource( new javax.media.MediaLocator(captureDeviceInfo.getLocator().toString())); // javax.media.protocol.DataSource dataSource = // javax.media.Manager.createDataSource(new // javax.media.MediaLocator("javasound://")); System.out.println("### created datasource " + dataSource.getClass().getName()); javax.media.control.FormatControl[] formatControls = ((javax.media.protocol.CaptureDevice) dataSource).getFormatControls(); System.out.println("got format control " + formatControls[0].getClass().getName()); System.out.println("current format is " + formatControls[0].getFormat()); // set audio capture format javax.media.Format[] formats = formatControls[0].getSupportedFormats(); for (int i = 0; i < formats.length; i++) { javax.media.format.AudioFormat af = (javax.media.format.AudioFormat) formats[i]; if ((af.getChannels() == 1) && (af.getSampleSizeInBits() == 16)) { if (af.getSampleRate() == Format.NOT_SPECIFIED) { javax.media.format.AudioFormat newAudioFormat = new javax.media.format.AudioFormat( af.getEncoding(), 8000.0f, javax.media.Format.NOT_SPECIFIED, javax.media.Format.NOT_SPECIFIED); // javax.media.format.AudioFormat newAudioFormat = new // javax.media.format.AudioFormat(af.getEncoding(), // 44100.0f, javax.media.Format.NOT_SPECIFIED, // javax.media.Format.NOT_SPECIFIED); formatControls[0].setFormat(newAudioFormat.intersects(af)); break; } } } System.out.println("current format is now " + formatControls[0].getFormat()); FrameProcessingControl fpc = null; // adujst recording buffer ( to adjust latency ) dataSource.stop(); Object[] controls = dataSource.getControls(); for (int i = 0; i < controls.length; i++) { String className = controls[i].getClass().getName(); if (-1 != className.indexOf("JavaSoundBufferControl")) { javax.media.control.BufferControl bc = (javax.media.control.BufferControl) controls[i]; System.out.println( "### current javasound buffer length is " + bc.getBufferLength() + " ms"); bc.setBufferLength(40); System.out.println( "### current javasound buffer length is " + bc.getBufferLength() + " ms"); } else if (-1 != className.indexOf("JitterBufferControl")) { javax.media.control.BufferControl bc = (javax.media.control.BufferControl) controls[i]; System.out.println("### current jitter buffer length is " + bc.getBufferLength() + " ms"); bc.setBufferLength(80); System.out.println("### current jitter buffer length is " + bc.getBufferLength() + " ms"); } else if (-1 != className.indexOf("FPC")) { fpc = (FrameProcessingControl) controls[i]; System.out.println("### found bitrate control " + fpc.getClass()); } } dataSource.start(); // create processor javax.media.Processor processor = javax.media.Manager.createProcessor(dataSource); System.out.println("### created processor " + processor.getClass().getName()); processor.configure(); for (int idx = 0; idx < 100; idx++) { if (processor.getState() == Processor.Configured) { break; } Thread.sleep(100); } System.out.println("### processor state " + processor.getState()); processor.setContentDescriptor( new javax.media.protocol.ContentDescriptor(ContentDescriptor.RAW_RTP)); javax.media.control.TrackControl[] tracks = processor.getTrackControls(); // /tracks[0].setFormat(new // javax.media.format.AudioFormat(javax.media.format.AudioFormat.ULAW_RTP, // 8000, 8, 1)); tracks[0].setFormat( new javax.media.format.AudioFormat(javax.media.format.AudioFormat.GSM_RTP, 8000, 8, 1)); processor.realize(); for (int idx = 0; idx < 100; idx++) { if (processor.getState() == Controller.Realized) { break; } Thread.sleep(100); } System.out.println("### processor state " + processor.getState()); javax.media.protocol.DataSource dataOutput = processor.getDataOutput(); System.out.println("### processor data output " + dataOutput.getClass().getName()); // BitRateControl BitRateControl bitrateControl = null; Object[] controls2 = dataOutput.getControls(); for (int i = 0; i < controls2.length; i++) { if (controls2[i] instanceof BitRateControl) { bitrateControl = (BitRateControl) controls2[i]; System.out.println("### found bitrate control " + bitrateControl.getClass()); break; } } // PacketSizeControl Object[] controls3 = processor.getControls(); for (int i = 0; i < controls3.length; i++) { if (controls3[i] instanceof PacketSizeControl) { PacketSizeControl psc = (PacketSizeControl) controls3[i]; System.out.println("### current packetsize is " + psc.getPacketSize() + " bytes"); psc.setPacketSize(66); System.out.println("### current packetsize is " + psc.getPacketSize() + " bytes"); break; } } // enumerate all controls of the processor Object[] pcontrols = processor.getControls(); for (int i = 0; i < pcontrols.length; i++) { System.out.println("processor control " + i + " " + pcontrols[i]); } javax.media.rtp.RTPManager rtpManager = javax.media.rtp.RTPManager.newInstance(); javax.media.rtp.SessionAddress local = new javax.media.rtp.SessionAddress( InetAddress.getLocalHost(), Integer.valueOf(args[1]).intValue()); javax.media.rtp.SessionAddress target = new javax.media.rtp.SessionAddress( InetAddress.getByName(args[0]), Integer.valueOf(args[1]).intValue()); rtpManager.initialize(local); rtpManager.addTarget(target); javax.media.rtp.SendStream sendStream = rtpManager.createSendStream(dataOutput, 0); sendStream.start(); processor.start(); Thread.sleep(1000); System.out.println("\n>>>>>> TRANSMITTING ULAW/RTP AUDIO NOW"); while (2 > 1) { Thread.sleep(1000); if (null != bitrateControl) { TransmissionStats stats = sendStream.getSourceTransmissionStats(); System.out.println( "rtp audio send: bitrate=" + bitrateControl.getBitRate() + " (pdu=" + stats.getPDUTransmitted() + " bytes=" + stats.getBytesTransmitted() + " overrun=" + fpc.getFramesDropped() + ")"); } } } catch (Exception ex) { ex.printStackTrace(); } System.exit(0); }
/** * Implements {@link ReceiveStreamListener#update(ReceiveStreamEvent)}. * * <p>{@link #rtpManager} will use this to notify us of <tt>ReceiveStreamEvent</tt>s. */ @Override public void update(ReceiveStreamEvent event) { if (event == null) return; ReceiveStream receiveStream = event.getReceiveStream(); if (event instanceof NewReceiveStreamEvent) { if (receiveStream == null) { logger.warn("NewReceiveStreamEvent: null"); return; } final long ssrc = getReceiveStreamSSRC(receiveStream); ReceiveStreamDesc receiveStreamDesc = findReceiveStream(ssrc); if (receiveStreamDesc != null) { String s = "NewReceiveStreamEvent for an existing SSRC. "; if (receiveStream != receiveStreamDesc.receiveStream) s += "(but different ReceiveStream object)"; logger.warn(s); return; } else receiveStreamDesc = new ReceiveStreamDesc(receiveStream); if (logger.isInfoEnabled()) logger.info("New ReceiveStream, ssrc=" + ssrc); // Find the format of the ReceiveStream DataSource dataSource = receiveStream.getDataSource(); if (dataSource instanceof PushBufferDataSource) { Format format = null; PushBufferDataSource pbds = (PushBufferDataSource) dataSource; for (PushBufferStream pbs : pbds.getStreams()) { if ((format = pbs.getFormat()) != null) break; } if (format == null) { logger.error("Failed to handle new ReceiveStream: " + "Failed to determine format"); return; } receiveStreamDesc.format = format; } else { logger.error("Failed to handle new ReceiveStream: " + "Unsupported DataSource"); return; } int rtpClockRate = -1; if (receiveStreamDesc.format instanceof AudioFormat) rtpClockRate = (int) ((AudioFormat) receiveStreamDesc.format).getSampleRate(); else if (receiveStreamDesc.format instanceof VideoFormat) rtpClockRate = 90000; getSynchronizer().setRtpClockRate(ssrc, rtpClockRate); // create a Processor and configure it Processor processor = null; try { processor = Manager.createProcessor(receiveStream.getDataSource()); } catch (NoProcessorException npe) { logger.error("Failed to create Processor: ", npe); return; } catch (IOException ioe) { logger.error("Failed to create Processor: ", ioe); return; } if (logger.isInfoEnabled()) logger.info("Created processor for SSRC=" + ssrc); processor.addControllerListener(this); receiveStreamDesc.processor = processor; final int streamCount; synchronized (receiveStreams) { receiveStreams.add(receiveStreamDesc); streamCount = receiveStreams.size(); } /* * XXX TODO IRBABOON * This is a terrible hack which works around a failure to realize() * some of the Processor-s for audio streams, when multiple streams * start nearly simultaneously. The cause of the problem is currently * unknown (and synchronizing all FMJ calls in RecorderRtpImpl * does not help). * XXX TODO NOOBABRI */ if (receiveStreamDesc.format instanceof AudioFormat) { final Processor p = processor; new Thread() { @Override public void run() { // delay configuring the processors for the different // audio streams to decrease the probability that they // run together. try { int ms = 450 * (streamCount - 1); logger.warn( "Sleeping for " + ms + "ms before" + " configuring processor for SSRC=" + ssrc + " " + System.currentTimeMillis()); Thread.sleep(ms); } catch (Exception e) { } p.configure(); } }.run(); } else { processor.configure(); } } else if (event instanceof TimeoutEvent) { if (receiveStream == null) { // TODO: we might want to get the list of ReceiveStream-s from // rtpManager and compare it to our list, to see if we should // remove a stream. logger.warn("TimeoutEvent: null."); return; } // FMJ silently creates new ReceiveStream instances, so we have to // recognize them by the SSRC. ReceiveStreamDesc receiveStreamDesc = findReceiveStream(getReceiveStreamSSRC(receiveStream)); if (receiveStreamDesc != null) { if (logger.isInfoEnabled()) { logger.info("ReceiveStream timeout, ssrc=" + receiveStreamDesc.ssrc); } removeReceiveStream(receiveStreamDesc, true); } } else if (event != null && logger.isInfoEnabled()) { logger.info("Unhandled ReceiveStreamEvent (" + event.getClass().getName() + "): " + event); } }
/** * Given an array of input media locators and an output locator, this method will concatenate the * input media files to generate a single concatentated output. */ public boolean doIt(MediaLocator inML[], MediaLocator outML) { // Guess the output content descriptor from the file extension. ContentDescriptor cd; if ((cd = fileExtToCD(outML.getRemainder())) == null) { System.err.println("Couldn't figure out from the file extension the type of output needed!"); return false; } // Build the ProcInfo data structure for each processor. ProcInfo pInfo[] = new ProcInfo[inML.length]; for (int i = 0; i < inML.length; i++) { pInfo[i] = new ProcInfo(); pInfo[i].ml = inML[i]; try { System.err.println("- Create processor for: " + inML[i]); pInfo[i].p = Manager.createProcessor(inML[i]); } catch (Exception e) { System.err.println("Yikes! Cannot create a processor from the given url: " + e); return false; } } // Try to match the tracks from different processors. if (!matchTracks(pInfo, cd)) { System.err.println("Failed to match the tracks."); return false; } // Program each processors to perform the necessary transcoding // to concatenate the tracks. if (!buildTracks(pInfo)) { System.err.println("Failed to build processors for the inputs."); return false; } // Generate a super glue data source from the processors. SuperGlueDataSource ds = new SuperGlueDataSource(pInfo); // Create the processor to generate the final output. Processor p; try { p = Manager.createProcessor(ds); } catch (Exception e) { System.err.println("Failed to create a processor to concatenate the inputs."); return false; } p.addControllerListener(this); // Put the Processor into configured state. if (!waitForState(p, Processor.Configured)) { System.err.println("Failed to configure the processor."); return false; } // Set the output content descriptor on the final processor. System.err.println("- Set output content descriptor to: " + cd); if ((p.setContentDescriptor(cd)) == null) { System.err.println("Failed to set the output content descriptor on the processor."); return false; } // We are done with programming the processor. Let's just // realize it. if (!waitForState(p, Controller.Realized)) { System.err.println("Failed to realize the processor."); return false; } // Now, we'll need to create a DataSink. DataSink dsink; if ((dsink = createDataSink(p, outML)) == null) { System.err.println("Failed to create a DataSink for the given output MediaLocator: " + outML); return false; } dsink.addDataSinkListener(this); fileDone = false; System.err.println("- Start concatenation..."); // OK, we can now start the actual concatenation. try { p.start(); dsink.start(); } catch (IOException e) { System.err.println("IO error during concatenation"); return false; } // Wait for EndOfStream event. waitForFileDone(); // Cleanup. try { dsink.close(); } catch (Exception e) { } p.removeControllerListener(this); System.err.println(" ...done concatenation."); return true; }
private String createProcessor() { if (locator == null) return "Locator is null"; DataSource ds; DataSource clone; try { ds = Manager.createDataSource(locator); } catch (Exception e) { return "Couldn't create DataSource"; } // Try to create a processor to handle the input media locator try { processor = Manager.createProcessor(ds); } catch (NoProcessorException npe) { return "Couldn't create processor"; } catch (IOException ioe) { return "IOException creating processor"; } // Wait for it to configure boolean result = waitForState(processor, Processor.Configured); if (result == false) return "Couldn't configure processor"; // Get the tracks from the processor TrackControl[] tracks = processor.getTrackControls(); // Do we have atleast one track? if (tracks == null || tracks.length < 1) return "Couldn't find tracks in processor"; boolean programmed = false; // Search through the tracks for a video track for (int i = 0; i < tracks.length; i++) { Format format = tracks[i].getFormat(); if (tracks[i].isEnabled() && format instanceof VideoFormat && !programmed) { // Found a video track. Try to program it to output JPEG/RTP // Make sure the sizes are multiple of 8's. Dimension size = ((VideoFormat) format).getSize(); float frameRate = ((VideoFormat) format).getFrameRate(); int w = (size.width % 8 == 0 ? size.width : (int) (size.width / 8) * 8); int h = (size.height % 8 == 0 ? size.height : (int) (size.height / 8) * 8); VideoFormat jpegFormat = new VideoFormat( VideoFormat.JPEG_RTP, new Dimension(w, h), Format.NOT_SPECIFIED, Format.byteArray, frameRate); tracks[i].setFormat(jpegFormat); System.err.println("Video transmitted as:"); System.err.println(" " + jpegFormat); // Assume succesful programmed = true; } else tracks[i].setEnabled(false); } if (!programmed) return "Couldn't find video track"; // Set the output content descriptor to RAW_RTP ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP); processor.setContentDescriptor(cd); // Realize the processor. This will internally create a flow // graph and attempt to create an output datasource for JPEG/RTP // video frames. result = waitForState(processor, Controller.Realized); if (result == false) return "Couldn't realize processor"; // Set the JPEG quality to .5. setJPEGQuality(processor, 0.5f); // Get the output data source of the processor dataOutput = processor.getDataOutput(); return null; }