コード例 #1
0
  public static void main1(String[] args) throws IOException, ClassNotFoundException {
    Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
    carl.setSecretary(harry);
    Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
    tony.setSecretary(harry);

    Employee[] staff = new Employee[3];
    staff[0] = carl;
    staff[1] = harry;
    staff[2] = tony;

    // save all employee records to the file employee.dat
    try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"))) {
      out.writeObject(staff);
    }
    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"))) {
      // retrieve all records into a new array
      Employee[] newStaff = (Employee[]) in.readObject();
      //          raise secretary's salary
      newStaff[1].raiseSalary(10);
      // print the newly read employee records
      for (Employee e : newStaff) System.out.println(e);
    }
  }
コード例 #2
0
  @Override
  public void update() {
    if (!transmitting) {
      super.update();

      ArrayList deadMonsters = new ArrayList();

      Monster monster = null;

      try {
        for (String key : monsters.keySet()) {
          monster = (Monster) monsters.get(key);
          if (monster != null) {
            monster.update();
            if (monster.getIsDead()) {
              deadMonsters.add(key);
            }
          }
        }

        if (deadMonsters.size() > 0) {
          for (int i = 0; i < deadMonsters.size(); i++) {
            // EIError.debugMsg((String) deadMonsters.get(i));
            monsters.remove((String) deadMonsters.get(i));
          }
        }
      } catch (ConcurrentModificationException concEx) {
        // another thread was trying to modify monsters while iterating
        // we'll continue and the new item can be grabbed on the next update
      }
    }
  }
コード例 #3
0
  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);
  }
  private void showCamera() {

    try {

      releaseResources();
      player = Manager.createPlayer("capture://video");
      player.addPlayerListener(this);
      player.realize();

      videoControl = (VideoControl) player.getControl("VideoControl");
      aVideoCanvas = new VideoCanvas();
      aVideoCanvas.initControls(videoControl, player);

      aVideoCanvas.addCommand(CMD_RECORD);
      aVideoCanvas.addCommand(CMD_EXIT);
      aVideoCanvas.setCommandListener(this);
      parentMidlet.getDisplay().setCurrent(aVideoCanvas);

      player.start();
      contentType = player.getContentType();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
  public void setMainSource() {
    setProcessing(false);
    VideoFormat vidformat = new VideoFormat(VideoFormat.RGB);
    Vector devices = CaptureDeviceManager.getDeviceList(vidformat);
    CaptureDeviceInfo di = null;

    if (devices.size() > 0) di = (CaptureDeviceInfo) devices.elementAt(0);
    else {
      JOptionPane.showMessageDialog(
          parent, "Your camera is not connected", "No webcam found", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      ml = di.getLocator();
      setMainCamSource(Manager.createDataSource(ml));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
          parent,
          "Exception locating media: " + e.getMessage(),
          "Error",
          JOptionPane.WARNING_MESSAGE);
      return;
    }
  }
コード例 #6
0
  private InputStream getInputStream(
      String urlStr, Format outputFormat, ContentDescriptor outputContentDescriptor)
      throws Exception {
    final ProcessorModel processorModel =
        new ProcessorModel(
            new MediaLocator(urlStr),
            outputFormat == null ? null : new Format[] {outputFormat},
            outputContentDescriptor);

    final Processor processor = Manager.createRealizedProcessor(processorModel);

    final DataSource ds = processor.getDataOutput();

    final DataSink[] streamDataSinkHolder = new DataSink[] {null};
    // connect the data output of the processor to a StreamDataSink, which
    // will make the data available to PipedInputStream, which we return.
    final PipedInputStream in =
        new PipedInputStream() {
          // override close to clean up everything when the media has been
          // served.
          @Override
          public void close() throws IOException {
            super.close();
            logger.fine("Closed input stream");
            logger.fine("Stopping processor");
            processor.stop();
            logger.fine("Closing processor");
            processor.close();
            logger.fine("Deallocating processor");
            processor.deallocate();
            if (streamDataSinkHolder[0] != null) {
              logger.fine("Closing StreamDataSink");
              streamDataSinkHolder[0].close();
            }
          }
        };
    final PipedOutputStream out = new PipedOutputStream(in);
    final DataSink streamDataSink = new StreamDataSink(out);
    streamDataSinkHolder[0] = streamDataSink;

    streamDataSink.setSource(ds);
    streamDataSink.open();
    streamDataSink.start();

    logger.info("Starting processor");
    processor.start();

    // TODO: if there is an error, make sure we clean up.
    // for example, if the client breaks the connection.
    // we need a controller listener to listen for errors.

    return in;
  }
コード例 #7
0
ファイル: RecorderRtpImpl.java プロジェクト: natib/libjitsi
  /**
   * Restarts the recording for a specific SSRC.
   *
   * @param ssrc the SSRC for which to restart recording. RTP packet of the new recording).
   */
  private void resetRecording(long ssrc, long timestamp) {
    ReceiveStreamDesc receiveStream = findReceiveStream(ssrc);

    // we only restart audio recordings
    if (receiveStream != null && receiveStream.format instanceof AudioFormat) {
      String newFilename = getNextFilename(path + "/" + ssrc, AUDIO_FILENAME_SUFFIX);

      // flush the buffer contained in the MP3 encoder
      String s = "trying to flush ssrc=" + ssrc;
      Processor p = receiveStream.processor;
      if (p != null) {
        s += " p!=null";
        for (TrackControl tc : p.getTrackControls()) {
          Object o = tc.getControl(FlushableControl.class.getName());
          if (o != null) ((FlushableControl) o).flush();
        }
      }

      if (logger.isInfoEnabled()) {
        logger.info("Restarting recording for SSRC=" + ssrc + ". New filename: " + newFilename);
      }

      receiveStream.dataSink.close();
      receiveStream.dataSink = null;

      // flush the FMJ jitter buffer
      // DataSource ds = receiveStream.receiveStream.getDataSource();
      // if (ds instanceof net.sf.fmj.media.protocol.rtp.DataSource)
      //    ((net.sf.fmj.media.protocol.rtp.DataSource)ds).flush();

      receiveStream.filename = newFilename;
      try {
        receiveStream.dataSink =
            Manager.createDataSink(
                receiveStream.dataSource, new MediaLocator("file:" + newFilename));
      } catch (NoDataSinkException ndse) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ndse);
        removeReceiveStream(receiveStream, false);
      }

      try {
        receiveStream.dataSink.open();
        receiveStream.dataSink.start();
      } catch (IOException ioe) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ioe);
        removeReceiveStream(receiveStream, false);
      }

      audioRecordingStarted(ssrc, timestamp);
    }
  }
コード例 #8
0
ファイル: h4Jmf.java プロジェクト: jkoppel/javaparser-to-hs
  public void player_begin(URL url) {
    if (h4JmfPlugin.playMP3 != null) {
      logger.severe("playMP3!=null");
      h4JmfPlugin.cnsl.append("playMP3!=null");
      return;
    }
    if (url == null) {
      h4JmfPlugin.cnsl.append("url==null");
      return;
    }
    MediaLocator mediaLocator = new MediaLocator(url);
    try {
      // final JPanel jpnl_this=this;

      DataSource ds = Manager.createDataSource(mediaLocator);
      // cnsl.append("ds="+ds);
      h4JmfPlugin.playMP3 = Manager.createPlayer(ds);
      /**
       * ********************************************************** ControllerListener moved to
       * outer class addControllerListener done in h4JmfPlugin **********************************
       */
      h4JmfPlugin.player_begin();
    } catch (Exception e) {
      logger.severe(e.getMessage());
      h4JmfPlugin.cnsl.append(e);
      return;
    }
    // h4JmfPlugin.playMP3.realize();
    // logger.info("after realize()");
    // but possible [JMF thread: com.sun.media.PlaybackEngine@1ac13d7[
    // com.sun.media.PlaybackEngine@1ac13d7 ] ( realizeThread)] [error] PlaybackEngine@1ac13d7 ] (
    // realizeThread):   Unable to handle format: mpeglayer3, 16000.0 Hz, 16-bit, Mono,
    // LittleEndian, Signed, 2000.0 frame rate, FrameSize=16384 bits
    // running tshvr under hedwig :11:17:08 PM [JMF thread:
    // com.sun.media.content.unknown.Handler@8c7be5 ( prefetchThread)] [error] Handler@8c7be5 (
    // prefetchThread): Error: Unable to prefetch com.sun.media.PlaybackEngine@6d3b92
  } // player_begin
コード例 #9
0
  @Override
  public void setTransient(Registry rg) {
    super.setTransient(rg);

    spawnCoolDowns = new HashMap<String, Integer>();

    try {
      for (String key : monsters.keySet()) {
        Monster monster = (Monster) monsters.get(key);
        monster.setTransient(rg, this);
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }
  }
コード例 #10
0
  /** @param args */
  public static void main(String[] args) {
    String url = "rtp://192.168.1.1:22224/audio/16";

    MediaLocator mrl = new MediaLocator(url);

    // Create a player for this rtp session
    Player player = null;
    try {
      player = Manager.createPlayer(mrl);
    } catch (NoPlayerException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    if (player != null) {
      System.out.println("Player created.");
      player.realize();
      // wait for realizing
      while (player.getState() != Controller.Realized) {
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("Starting player");
      player.start();
    } else {
      System.err.println("Player doesn't created.");
      System.exit(-1);
    }

    System.out.println("Exiting.");
  }
コード例 #11
0
  public static void main(String args[]) throws Exception {

    // Take the path of the audio file from command line

    File f = new File("C:\\Users\\Larry\\AppData\\Local\\Temp\\jgoogle_tts-588881786930740869.mp3");
    // Create a Player object that realizes the audio
    final Player p = Manager.createRealizedPlayer(f.toURI().toURL());
    // Start the music
    p.start();
    // Create a Scanner object for taking input from cmd
    Scanner s = new Scanner(System.in);

    // Read a line and store it in st

    String st = s.nextLine();

    // If user types 's', stop the audio

    if (st.equals("s")) {

      p.stop();
    }
  }
コード例 #12
0
ファイル: Recorder.java プロジェクト: davidkeen/tuner
  /**
   * Creates a new instance of Recorder
   *
   * @param buffer the shared Buffer.
   * @param controller the controlling TunerMIDlet instance.
   */
  public Recorder(Buffer buffer, TunerMIDlet controller) {
    this.buffer = buffer;
    this.controller = controller;

    // Buffer filling time (s) is FFT length / sample rate (* 1000ms).
    recordingTime = 1000 * controller.getSampleLength() / TunerMIDlet.RATE;

    if (capturePlayer == null) {
      try {
        capturePlayer =
            Manager.createPlayer("capture://audio?encoding=pcm&rate=" + TunerMIDlet.RATE);

        capturePlayer.realize();
        recordControl = (RecordControl) capturePlayer.getControl("RecordControl");

        // Create the internal buffer for the recording
        bos = new ByteArrayOutputStream(controller.getSampleLength());
      } catch (Exception e) {
        // No point continuing without a capturePlayer or recordControl so show fatal error.
        controller.showError(e.getMessage(), new FatalForm(controller));
      }
    }
  }
コード例 #13
0
ファイル: VideoTransmit.java プロジェクト: sourabhg/VidcoFed
  // Creates an RTP transmit data sink. This is the easiest way to create
  // an RTP transmitter. The other way is to use the RTPSessionManager API.
  // Using an RTP session manager gives you more control if you wish to
  // fine tune your transmission and set other parameters.
  private String createTransmitter() {
    // Create a media locator for the RTP data sink.
    // For example:
    //    rtp://129.130.131.132:42050/video
    String rtpURL = "rtp://" + ipAddress + ":" + port + "/video";
    MediaLocator outputLocator = new MediaLocator(rtpURL);

    // Create a data sink, open it and start transmission. It will wait
    // for the processor to start sending data. So we need to start the
    // output data source of the processor. We also need to start the
    // processor itself, which is done after this method returns.
    try {
      rtptransmitter = Manager.createDataSink(dataOutput, outputLocator);
      rtptransmitter.open();
      rtptransmitter.start();
      dataOutput.start();
    } catch (MediaException me) {
      return "Couldn't create RTP data sink";
    } catch (IOException ioe) {
      return "Couldn't create RTP data sink";
    }

    return null;
  }
コード例 #14
0
 public void makeDataSourceCloneable() {
   // turn our data source to a cloneable data source
   setMainCamSource(Manager.createCloneableDataSource(getMainCamSource()));
 }
コード例 #15
0
  public WebcamCaptureAndFadePanel(String saveDir, String layout) {

    System.out.println("Using " + saveDir + " as directory for the images.");
    saveDirectory = saveDir;

    getImages();
    images_used = new ArrayList<Integer>();
    images_lastadded = new ArrayList<Integer>();
    images_nevershown = new ArrayList<Integer>();

    Vector devices = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
    Enumeration enumeration = devices.elements();
    System.out.println("- Available cameras -");
    ArrayList<String> names = new ArrayList<String>();
    while (enumeration.hasMoreElements()) {
      CaptureDeviceInfo cdi = (CaptureDeviceInfo) enumeration.nextElement();
      String name = cdi.getName();
      if (name.startsWith("vfw:")) {
        names.add(name);
        System.out.println(name);
      }
    }

    // String str1 = "vfw:Logitech USB Video Camera:0";
    // String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
    if (names.size() == 0) {
      JOptionPane.showMessageDialog(
          null,
          "Ingen kamera funnet. " + "Du må koble til et kamera for å kjøre programmet.",
          "Feil",
          JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    } else if (names.size() > 1) {

      JOptionPane.showMessageDialog(
          null,
          "Fant mer enn 1 kamera. " + "Velger da:\n" + names.get(0),
          "Advarsel",
          JOptionPane.WARNING_MESSAGE);
    }

    String str2 = names.get(0);
    di = CaptureDeviceManager.getDevice(str2);
    ml = di.getLocator();

    try {
      player = Manager.createRealizedPlayer(ml);
      formatControl = (FormatControl) player.getControl("javax.media.control.FormatControl");

      /*
      Format[] formats = formatControl.getSupportedFormats();
      for (int i=0; i<formats.length; i++)
      	System.out.println(formats[i].toString());
      */

      player.start();
    } catch (javax.media.NoPlayerException e) {
      JOptionPane.showMessageDialog(
          null,
          "Klarer ikke å starte" + " programmet pga. feil med kamera. Sjekk at det er koblet til.",
          "IOException",
          JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }

    /*
     * Layout
     *
     * Add
     * - comp
     * - imagepanels
     */

    if (layout.equals("1024v2")) {
      layout1024v2();
    } else if (layout.equals("1280")) {
      layout1280();
    } else {
      layout1024();
    }

    // Capture Window
    if (captureWindow) {
      cw = new JFrame("Capture from webcam");
      cw.setAlwaysOnTop(true);
      cw.setSize(sizeCaptureWindow_x, sizeCaptureWindow_y);
      cw.addKeyListener(new captureWindowKeyListner());
      cw.setUndecorated(true);

      // Add webcam
      if ((comp = player.getVisualComponent()) != null) {
        cw.add(comp);
      }

      // Add panel to window and set location of window
      cw.setLocation(cwLocation_x, cwLocation_y);
    }

    // Text window
    cwText = new rotatedText("");

    /*
     * Timer for update
     */
    Timer thread = new Timer();
    thread.schedule(new frameUpdateTask(), 0, (1000 / fps));
  }
コード例 #16
0
ファイル: Example5_6.java プロジェクト: elecnix/jmf
  public static void main(String[] args) {

    // ---------------- CUT HERE START ----------------- //

    Format formats[] = new Format[2];
    formats[0] = new AudioFormat(AudioFormat.IMA4);
    formats[1] = new VideoFormat(VideoFormat.CINEPAK);
    FileTypeDescriptor outputType = new FileTypeDescriptor(FileTypeDescriptor.QUICKTIME);
    Processor p = null;

    try {
      p = Manager.createRealizedProcessor(new ProcessorModel(formats, outputType));
    } catch (IOException e) {
      System.exit(-1);
    } catch (NoProcessorException e) {
      System.exit(-1);
    } catch (CannotRealizeException e) {
      System.exit(-1);
    }
    // get the output of the processor
    DataSource source = p.getDataOutput();
    // create a File protocol MediaLocator with the location of the file to
    // which bits are to be written
    MediaLocator dest = new MediaLocator("file://foo.mov");
    // create a datasink to do the file writing & open the sink to make sure
    // we can write to it.
    DataSink filewriter = null;
    try {
      filewriter = Manager.createDataSink(source, dest);
      filewriter.open();
    } catch (NoDataSinkException e) {
      System.exit(-1);
    } catch (IOException e) {
      System.exit(-1);
    } catch (SecurityException e) {
      System.exit(-1);
    }
    // now start the filewriter and processor
    try {
      filewriter.start();
    } catch (IOException e) {
      System.exit(-1);
    }
    p.start();
    // stop and close the processor when done capturing...
    // close the datasink when EndOfStream event is received...

    // ----------------- CUT HERE END ---------------- //
    try {
      Thread.currentThread().sleep(4000);
    } catch (InterruptedException ie) {
    }
    p.stop();
    p.close();
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException ie) {
    }
    filewriter.close();
    try {
      Thread.currentThread().sleep(4000);
    } catch (InterruptedException ie) {
    }

    System.exit(0);
  }
コード例 #17
0
ファイル: VideoTransmit.java プロジェクト: sourabhg/VidcoFed
  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;
  }
コード例 #18
0
ファイル: RecorderRtpImpl.java プロジェクト: natib/libjitsi
  /**
   * Implements {@link ControllerListener#controllerUpdate(ControllerEvent)}. Handles events from
   * the <tt>Processor</tt>s that this instance uses to transcode media.
   *
   * @param ev the event to handle.
   */
  public void controllerUpdate(ControllerEvent ev) {
    if (ev == null || ev.getSourceController() == null) {
      return;
    }

    Processor processor = (Processor) ev.getSourceController();
    ReceiveStreamDesc desc = findReceiveStream(processor);

    if (desc == null) {
      logger.warn("Event from an orphaned processor, ignoring: " + ev);
      return;
    }

    if (ev instanceof ConfigureCompleteEvent) {
      if (logger.isInfoEnabled()) {
        logger.info(
            "Configured processor for ReceiveStream ssrc="
                + desc.ssrc
                + " ("
                + desc.format
                + ")"
                + " "
                + System.currentTimeMillis());
      }

      boolean audio = desc.format instanceof AudioFormat;

      if (audio) {
        ContentDescriptor cd = processor.setContentDescriptor(AUDIO_CONTENT_DESCRIPTOR);
        if (!AUDIO_CONTENT_DESCRIPTOR.equals(cd)) {
          logger.error(
              "Failed to set the Processor content "
                  + "descriptor to "
                  + AUDIO_CONTENT_DESCRIPTOR
                  + ". Actual result: "
                  + cd);
          removeReceiveStream(desc, false);
          return;
        }
      }

      for (TrackControl track : processor.getTrackControls()) {
        Format trackFormat = track.getFormat();

        if (audio) {
          final long ssrc = desc.ssrc;
          SilenceEffect silenceEffect;
          if (Constants.OPUS_RTP.equals(desc.format.getEncoding())) {
            silenceEffect = new SilenceEffect(48000);
          } else {
            // We haven't tested that the RTP timestamps survive
            // the journey through the chain when codecs other than
            // opus are in use, so for the moment we rely on FMJ's
            // timestamps for non-opus formats.
            silenceEffect = new SilenceEffect();
          }

          silenceEffect.setListener(
              new SilenceEffect.Listener() {
                boolean first = true;

                @Override
                public void onSilenceNotInserted(long timestamp) {
                  if (first) {
                    first = false;
                    // send event only
                    audioRecordingStarted(ssrc, timestamp);
                  } else {
                    // change file and send event
                    resetRecording(ssrc, timestamp);
                  }
                }
              });
          desc.silenceEffect = silenceEffect;
          AudioLevelEffect audioLevelEffect = new AudioLevelEffect();
          audioLevelEffect.setAudioLevelListener(
              new SimpleAudioLevelListener() {
                @Override
                public void audioLevelChanged(int level) {
                  activeSpeakerDetector.levelChanged(ssrc, level);
                }
              });

          try {
            // We add an effect, which will insert "silence" in
            // place of lost packets.
            track.setCodecChain(new Codec[] {silenceEffect, audioLevelEffect});
          } catch (UnsupportedPlugInException upie) {
            logger.warn("Failed to insert silence effect: " + upie);
            // But do go on, a recording without extra silence is
            // better than nothing ;)
          }
        } else {
          // transcode vp8/rtp to vp8 (i.e. depacketize vp8)
          if (trackFormat.matches(vp8RtpFormat)) track.setFormat(vp8Format);
          else {
            logger.error("Unsupported track format: " + trackFormat + " for ssrc=" + desc.ssrc);
            // we currently only support vp8
            removeReceiveStream(desc, false);
            return;
          }
        }
      }

      processor.realize();
    } else if (ev instanceof RealizeCompleteEvent) {
      desc.dataSource = processor.getDataOutput();

      long ssrc = desc.ssrc;
      boolean audio = desc.format instanceof AudioFormat;
      String suffix = audio ? AUDIO_FILENAME_SUFFIX : VIDEO_FILENAME_SUFFIX;

      // XXX '\' on windows?
      String filename = getNextFilename(path + "/" + ssrc, suffix);
      desc.filename = filename;

      DataSink dataSink;
      if (audio) {
        try {
          dataSink = Manager.createDataSink(desc.dataSource, new MediaLocator("file:" + filename));
        } catch (NoDataSinkException ndse) {
          logger.error("Could not create DataSink: " + ndse);
          removeReceiveStream(desc, false);
          return;
        }

      } else {
        dataSink = new WebmDataSink(filename, desc.dataSource);
      }

      if (logger.isInfoEnabled())
        logger.info(
            "Created DataSink ("
                + dataSink
                + ") for SSRC="
                + ssrc
                + ". Output filename: "
                + filename);
      try {
        dataSink.open();
      } catch (IOException e) {
        logger.error("Failed to open DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ": " + e);
        removeReceiveStream(desc, false);
        return;
      }

      if (!audio) {
        final WebmDataSink webmDataSink = (WebmDataSink) dataSink;
        webmDataSink.setSsrc(ssrc);
        webmDataSink.setEventHandler(eventHandler);
        webmDataSink.setKeyFrameControl(
            new KeyFrameControlAdapter() {
              @Override
              public boolean requestKeyFrame(boolean urgent) {
                return requestFIR(webmDataSink);
              }
            });
      }

      try {
        dataSink.start();
      } catch (IOException e) {
        logger.error(
            "Failed to start DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ". " + e);
        removeReceiveStream(desc, false);
        return;
      }

      if (logger.isInfoEnabled()) logger.info("Started DataSink for SSRC=" + ssrc);

      desc.dataSink = dataSink;

      processor.start();
    } else if (logger.isDebugEnabled()) {
      logger.debug(
          "Unhandled ControllerEvent from the Processor for ssrc=" + desc.ssrc + ": " + ev);
    }
  }
コード例 #19
0
ファイル: RecorderRtpImpl.java プロジェクト: natib/libjitsi
  /**
   * 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);
    }
  }