org.kurento.client.EventListener Java Examples

The following examples show how to use org.kurento.client.EventListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompositeWrapper.java    From openvidu with Apache License 2.0 6 votes vote down vote up
public synchronized void stopCompositeRecording(CountDownLatch stopLatch, Long timeOfKmsDisconnection) {
	if (timeOfKmsDisconnection == 0) {
		this.recorderEndpoint.addStoppedListener(new EventListener<StoppedEvent>() {
			@Override
			public void onEvent(StoppedEvent event) {
				endTime = Long.parseLong(event.getTimestampMillis());
				log.info("Recording stopped event for audio-only RecorderEndpoint of Composite in session {}",
						session.getSessionId());
				recorderEndpoint.release();
				compositeToRecorderHubPort.release();
				stopLatch.countDown();
			}
		});
		this.recorderEndpoint.stop();
	} else {
		endTime = timeOfKmsDisconnection;
		stopLatch.countDown();
		log.warn("Forcing composed audio-only recording stop after KMS restart in session {}",
				this.session.getSessionId());
	}

}
 
Example #2
Source File: PlayMediaPipeline.java    From kurento-tutorial-java with Apache License 2.0 6 votes vote down vote up
public PlayMediaPipeline(KurentoClient kurento, String user, final WebSocketSession session) {
  // Media pipeline
  pipeline = kurento.createMediaPipeline();

  // Media Elements (WebRtcEndpoint, PlayerEndpoint)
  webRtc = new WebRtcEndpoint.Builder(pipeline).build();
  player = new PlayerEndpoint.Builder(pipeline, RECORDING_PATH + user + RECORDING_EXT).build();

  // Connection
  player.connect(webRtc);

  // Player listeners
  player.addErrorListener(new EventListener<ErrorEvent>() {
    @Override
    public void onEvent(ErrorEvent event) {
      log.info("ErrorEvent: {}", event.getDescription());
      sendPlayEnd(session);
    }
  });
}
 
Example #3
Source File: UserSession.java    From kurento-tutorial-java with Apache License 2.0 6 votes vote down vote up
public void stop() {
  if (recorderEndpoint != null) {
    final CountDownLatch stoppedCountDown = new CountDownLatch(1);
    ListenerSubscription subscriptionId = recorderEndpoint
        .addStoppedListener(new EventListener<StoppedEvent>() {

          @Override
          public void onEvent(StoppedEvent event) {
            stoppedCountDown.countDown();
          }
        });
    recorderEndpoint.stop();
    try {
      if (!stoppedCountDown.await(5, TimeUnit.SECONDS)) {
        log.error("Error waiting for recorder to stop");
      }
    } catch (InterruptedException e) {
      log.error("Exception while waiting for state change", e);
    }
    recorderEndpoint.removeStoppedListener(subscriptionId);
  }
}
 
Example #4
Source File: PlayMediaPipeline.java    From kurento-tutorial-java with Apache License 2.0 6 votes vote down vote up
public PlayMediaPipeline(KurentoClient kurento, String user, final WebSocketSession session) {
  // Media pipeline
  pipeline = kurento.createMediaPipeline();

  // Media Elements (WebRtcEndpoint, PlayerEndpoint)
  webRtc = new WebRtcEndpoint.Builder(pipeline).build();
  player = new PlayerEndpoint.Builder(pipeline, RECORDING_PATH + user + RECORDING_EXT).build();

  // Connection
  player.connect(webRtc);

  // Player listeners
  player.addErrorListener(new EventListener<ErrorEvent>() {
    @Override
    public void onEvent(ErrorEvent event) {
      log.info("ErrorEvent: {}", event.getDescription());
      sendPlayEnd(session);
    }
  });
}
 
Example #5
Source File: RemoteObjectInvocationHandler.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Object genericSubscribeEventListener(String eventName, final Object proxy, final Object[] args,
		Continuation<?> cont, Transaction tx) {

	RemoteObjectEventListener listener = new RemoteObjectEventListener() {
		@Override
		public void onEvent(String eventType, Props data) {
			propagateEventTo(proxy, GenericMediaEvent.class, data, (EventListener<?>) args[1]);
		}
	};

	if (cont != null) {
		remoteObject.addEventListener(eventName, listener, (Continuation<ListenerSubscriptionImpl>) cont);
		return null;
	} else if (tx != null) {
		return remoteObject.addEventListener(eventName, listener, tx);
	} else {
		return remoteObject.addEventListener(eventName, listener);
	}
}
 
Example #6
Source File: RemoteObjectInvocationHandler.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Object subscribeEventListener(final Object proxy, final Object[] args, String methodName,
    final Class<? extends Event> eventClass, Continuation<?> cont, Transaction tx) {

  String eventName = eventClass.getSimpleName().substring(0,
      eventClass.getSimpleName().length() - "Event".length());

  RemoteObjectEventListener listener = new RemoteObjectEventListener() {
    @Override
    public void onEvent(String eventType, Props data) {
      propagateEventTo(proxy, eventClass, data, (EventListener<?>) args[0]);
    }
  };

  if (cont != null) {
    remoteObject.addEventListener(eventName, listener,
        (Continuation<ListenerSubscriptionImpl>) cont);
    return null;
  } else if (tx != null) {
    return remoteObject.addEventListener(eventName, listener, tx);
  } else {
    return remoteObject.addEventListener(eventName, listener);
  }
}
 
Example #7
Source File: MediaEndpoint.java    From kurento-room with Apache License 2.0 6 votes vote down vote up
/**
 * If supported, it registers a listener for when a new {@link IceCandidate} is gathered by the
 * internal endpoint ({@link WebRtcEndpoint}) and sends it to the remote User Agent as a
 * notification using the messaging capabilities of the {@link Participant}.
 *
 * @see WebRtcEndpoint#addOnIceCandidateListener(org.kurento.client.EventListener)
 * @see Participant#sendIceCandidate(String, IceCandidate)
 * @throws RoomException
 *           if thrown, unable to register the listener
 */
protected void registerOnIceCandidateEventListener() throws RoomException {
  if (!this.isWeb()) {
    return;
  }
  if (webEndpoint == null) {
    throw new RoomException(Code.MEDIA_WEBRTC_ENDPOINT_ERROR_CODE,
        "Can't register event listener for null WebRtcEndpoint (ep: " + endpointName + ")");
  }
  webEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
    @Override
    public void onEvent(OnIceCandidateEvent event) {
      owner.sendIceCandidate(endpointName, event.getCandidate());
    }
  });
}
 
Example #8
Source File: SingleStreamRecordingService.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public void stopRecorderEndpointOfPublisherEndpoint(String sessionId, String streamId,
		CountDownLatch globalStopLatch, Long kmsDisconnectionTime) {
	log.info("Stopping single stream recorder for stream {} in session {}", streamId, sessionId);
	final RecorderEndpointWrapper finalWrapper = activeRecorders.get(sessionId).remove(streamId);
	if (finalWrapper != null && kmsDisconnectionTime == 0) {
		finalWrapper.getRecorder().addStoppedListener(new EventListener<StoppedEvent>() {
			@Override
			public void onEvent(StoppedEvent event) {
				finalWrapper.setEndTime(Long.parseLong(event.getTimestampMillis()));
				generateIndividualMetadataFile(finalWrapper);
				log.info("Recording stopped event for stream {}", streamId);
				finalWrapper.getRecorder().release();
				globalStopLatch.countDown();
			}
		});
		finalWrapper.getRecorder().stop();
	} else {
		if (kmsDisconnectionTime != 0) {
			// Stopping recorder endpoint because of a KMS disconnection
			finalWrapper.setEndTime(kmsDisconnectionTime);
			generateIndividualMetadataFile(finalWrapper);
			log.warn("Forcing individual recording stop after KMS restart for stream {} in session {}", streamId,
					sessionId);
		} else {
			if (storedRecorders.get(sessionId).containsKey(streamId)) {
				log.info("Stream {} recording of session {} was already stopped", streamId, sessionId);
			} else {
				log.error("Stream {} wasn't being recorded in session {}", streamId, sessionId);
			}
		}
		globalStopLatch.countDown();
	}
}
 
Example #9
Source File: MediaEndpoint.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
/**
 * Registers a listener for when the {@link MediaElement} triggers an {@link ErrorEvent}. Notifies
 * the owner with the error.
 *
 * @param element
 *          the {@link MediaElement}
 * @return {@link ListenerSubscription} that can be used to deregister the listener
 */
protected ListenerSubscription registerElemErrListener(MediaElement element) {
  return element.addErrorListener(new EventListener<ErrorEvent>() {
    @Override
    public void onEvent(ErrorEvent event) {
      owner.sendMediaError(event);
    }
  });
}
 
Example #10
Source File: RepositoryRecorderTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void launchBrowser(WebRtcEndpoint webRtcEp, PlayerEndpoint playerEp,
    RecorderEndpoint recorderEp) throws InterruptedException {

  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
  playerEp.play();
  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });

  if (recorderEp != null) {
    recorderEp.record();
  }

  // Assertions
  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage().waitForEvent("playing"));
  Assert.assertTrue("The color of the video should be black",
      getPage().similarColor(Color.BLACK));
  Assert.assertTrue("Not received EOS event in player",
      eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));
  double currentTime = getPage().getCurrentTime();
  Assert.assertTrue(
      "Error in play time (expected: " + PLAYTIME + " sec, real: " + currentTime + " sec)",
      getPage().compare(PLAYTIME, currentTime));
}
 
Example #11
Source File: MetaTestMountedVolumeTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws InterruptedException {

  // Media Pipeline
  MediaPipeline mp = kurentoClient.createMediaPipeline();

  String videoPath = "file://" + getTestFilesDiskPath() + "/video/filter/barcodes.webm";

  PlayerEndpoint p = new PlayerEndpoint.Builder(mp, videoPath).build();

  final CountDownLatch latch = new CountDownLatch(1);

  p.addErrorListener(new EventListener<ErrorEvent>() {
    @Override
    public void onEvent(ErrorEvent event) {
      log.warn("Error un player: " + event.getDescription());
      latch.countDown();
    }
  });

  p.play();

  if (latch.await(5, TimeUnit.SECONDS)) {
    fail("Player error");
  }

  // Release Media Pipeline
  mp.release();
}
 
Example #12
Source File: EventTagTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventWithoutTag() throws Exception {
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  final CountDownLatch eventReceived = new CountDownLatch(1);

  PlayerEndpoint player =
      new PlayerEndpoint.Builder(mp, "http://" + getTestFilesHttpPath() + "/video/10sec/red.webm")
          .build();

  player.addTag("test_1", "value_1");
  player.addTag("test_2", "value_2");
  player.addTag("test_3", "value_3");

  player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      List<Tag> tags = event.getTags();

      if (tags.size() == 0) {
        eventReceived.countDown();
      }
    }
  });

  player.play();
  // Guard time to reproduce the whole video
  if (!eventReceived.await(TIMEOUT, TimeUnit.SECONDS)) {
    Assert.fail("Event not received");
  }
}
 
Example #13
Source File: AsyncEventManager.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public EventListener<T> getMediaEventListener() {

    return new EventListener<T>() {
      @Override
      public void onEvent(T event) {
        addResult(event);
      }
    };
  }
 
Example #14
Source File: UserSession.java    From kurento-tutorial-java with Apache License 2.0 5 votes vote down vote up
public UserSession(final String name, String roomName, final WebSocketSession session,
    MediaPipeline pipeline) {

  this.pipeline = pipeline;
  this.name = name;
  this.session = session;
  this.roomName = roomName;
  this.outgoingMedia = new WebRtcEndpoint.Builder(pipeline).build();

  this.outgoingMedia.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

    @Override
    public void onEvent(IceCandidateFoundEvent event) {
      JsonObject response = new JsonObject();
      response.addProperty("id", "iceCandidate");
      response.addProperty("name", name);
      response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
      try {
        synchronized (session) {
          session.sendMessage(new TextMessage(response.toString()));
        }
      } catch (IOException e) {
        log.debug(e.getMessage());
      }
    }
  });
}
 
Example #15
Source File: UserSession.java    From kurento-tutorial-java with Apache License 2.0 5 votes vote down vote up
private WebRtcEndpoint getEndpointForUser(final UserSession sender) {
  if (sender.getName().equals(name)) {
    log.debug("PARTICIPANT {}: configuring loopback", this.name);
    return outgoingMedia;
  }

  log.debug("PARTICIPANT {}: receiving video from {}", this.name, sender.getName());

  WebRtcEndpoint incoming = incomingMedia.get(sender.getName());
  if (incoming == null) {
    log.debug("PARTICIPANT {}: creating new endpoint for {}", this.name, sender.getName());
    incoming = new WebRtcEndpoint.Builder(pipeline).build();

    incoming.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

      @Override
      public void onEvent(IceCandidateFoundEvent event) {
        JsonObject response = new JsonObject();
        response.addProperty("id", "iceCandidate");
        response.addProperty("name", sender.getName());
        response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
        try {
          synchronized (session) {
            session.sendMessage(new TextMessage(response.toString()));
          }
        } catch (IOException e) {
          log.debug(e.getMessage());
        }
      }
    });

    incomingMedia.put(sender.getName(), incoming);
  }

  log.debug("PARTICIPANT {}: obtained endpoint for {}", this.name, sender.getName());
  sender.getOutgoingWebRtcPeer().connect(incoming);

  return incoming;
}
 
Example #16
Source File: MediaEndpoint.java    From openvidu with Apache License 2.0 5 votes vote down vote up
/**
 * Registers a listener for when the {@link MediaElement} triggers an
 * {@link ErrorEvent}. Notifies the owner with the error.
 *
 * @param element the {@link MediaElement}
 * @return {@link ListenerSubscription} that can be used to deregister the
 *         listener
 */
protected ListenerSubscription registerElemErrListener(MediaElement element) {
	return element.addErrorListener(new EventListener<ErrorEvent>() {
		@Override
		public void onEvent(ErrorEvent event) {
			owner.sendMediaError(event);
		}
	});
}
 
Example #17
Source File: TestPipeline.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
public void createPipeline() {
  synchronized (pipelineCreateLock) {
    if (pipeline != null) {
      return;
    }
    log.info("Session '{}': Creating MediaPipeline-{}", room, description);
    try {
      pipeline = kurento.createMediaPipeline();
      pipelineLatch.countDown();
      log.debug("Session '{}': Created MediaPipeline-{}", room, description);
    } catch (Exception e) {
      log.error("Unable to create MediaPipeline-{} for Session '{}'", description, room, e);
      pipelineLatch.countDown();
    }
    if (getPipeline() == null) {
      throw new RuntimeException("Unable to create MediaPipeline-" + description
          + " for session '" + room + "'");
    }

    pipeline.addErrorListener(new EventListener<ErrorEvent>() {
      @Override
      public void onEvent(ErrorEvent event) {
        String desc = event.getType() + ": " + event.getDescription() + "(errCode="
            + event.getErrorCode() + ")";
        log.warn("Session '{}': Pipeline error encountered for MediaPipeline-{}: {}", room,
            description, desc);
      }
    });
  }
}
 
Example #18
Source File: LongStabilityRecorderS3Test.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(final MediaProfileSpecType mediaProfileSpecType, String expectedAudioCodec,
    final String extension) throws Exception {

  long testDurationMillis =
      PropertiesManager.getProperty(TEST_DURATION_PROPERTY, DEFAULT_TEST_DURATION);

  MediaPipeline mp = kurentoClient.createMediaPipeline();

  final CountDownLatch errorPipelinelatch = new CountDownLatch(1);

  mp.addErrorListener(new EventListener<ErrorEvent>() {

    @Override
    public void onEvent(ErrorEvent event) {
      msgError = "Description:" + event.getDescription() + "; Error code:" + event.getType();
      log.error(msgError);
      errorPipelinelatch.countDown();
    }
  });
  final WebRtcEndpoint webRtcSender = new WebRtcEndpoint.Builder(mp).build();

  // WebRTC sender negotiation
  getPage().subscribeLocalEvents("playing");
  getPage().initWebRtc(webRtcSender, WebRtcChannel.AUDIO_ONLY, WebRtcMode.SEND_ONLY);
  Assert.assertTrue("Not received media in sender webrtc", getPage().waitForEvent("playing"));

  // Recorder
  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorder = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();
  webRtcSender.connect(recorder);

  // Start recorder
  recorder.record();

  // Wait recording time
  Thread.sleep(testDurationMillis);

  // Stop recorder
  final CountDownLatch recorderLatch = new CountDownLatch(1);
  recorder.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  // Release Media Pipeline
  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));
  if (mp != null) {
    mp.release();
  }

  Assert.assertTrue(msgError, errorPipelinelatch.getCount() == 1);

  waitForFileExists(recordingFile);

  // Assessments
  AssertMedia.assertDuration(recordingFile, testDurationMillis, THRESHOLD_MS);

}
 
Example #19
Source File: KurentoSession.java    From openvidu with Apache License 2.0 4 votes vote down vote up
private void createPipeline() {
	synchronized (pipelineCreateLock) {
		if (pipeline != null) {
			return;
		}
		log.info("SESSION {}: Creating MediaPipeline", sessionId);
		try {
			kms.getKurentoClient().createMediaPipeline(new Continuation<MediaPipeline>() {
				@Override
				public void onSuccess(MediaPipeline result) throws Exception {
					pipeline = result;
					pipelineLatch.countDown();
					log.debug("SESSION {}: Created MediaPipeline", sessionId);
				}

				@Override
				public void onError(Throwable cause) throws Exception {
					pipelineCreationErrorCause = cause;
					pipelineLatch.countDown();
					log.error("SESSION {}: Failed to create MediaPipeline", sessionId, cause);
				}
			});
		} catch (Exception e) {
			log.error("Unable to create media pipeline for session '{}'", sessionId, e);
			pipelineLatch.countDown();
		}
		if (getPipeline() == null) {
			final String message = pipelineCreationErrorCause != null
					? pipelineCreationErrorCause.getLocalizedMessage()
					: "Unable to create media pipeline for session '" + sessionId + "'";
			pipelineCreationErrorCause = null;
			throw new OpenViduException(Code.ROOM_CANNOT_BE_CREATED_ERROR_CODE, message);
		}

		pipeline.addErrorListener(new EventListener<ErrorEvent>() {
			@Override
			public void onEvent(ErrorEvent event) {
				String desc = event.getType() + ": " + event.getDescription() + "(errCode=" + event.getErrorCode()
						+ ")";
				log.warn("SESSION {}: Pipeline error encountered: {}", sessionId, desc);
				kurentoSessionHandler.onPipelineError(sessionId, getParticipants(), desc);
			}
		});
	}
}
 
Example #20
Source File: WebRtcOneLoopbackTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebRtcLoopback() throws Exception {

  // Media Pipeline
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(mp).build();
  webRtcEndpoint.connect(webRtcEndpoint);

  final CountDownLatch flowingLatch = new CountDownLatch(1);
  webRtcEndpoint
      .addMediaFlowInStateChangeListener(new EventListener<MediaFlowInStateChangeEvent>() {

        @Override
        public void onEvent(MediaFlowInStateChangeEvent event) {
          if (event.getState().equals(MediaFlowState.FLOWING)) {
            flowingLatch.countDown();
          }
        }
      });

  // Start WebRTC and wait for playing event
  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEndpoint, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_RCV);

  Assert.assertTrue("Not received FLOWING IN event in webRtcEp: " + WebRtcChannel.AUDIO_AND_VIDEO,
      flowingLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  Assert.assertTrue(
      "Not received media (timeout waiting playing event): " + WebRtcChannel.AUDIO_AND_VIDEO,
      getPage().waitForEvent("playing"));

  // Guard time to play the video
  waitSeconds(PLAYTIME);

  // Assertions
  double currentTime = getPage().getCurrentTime();
  Assert.assertTrue(
      "Error in play time (expected: " + PLAYTIME + " sec, real: " + currentTime + " sec)",
      getPage().compare(PLAYTIME, currentTime));
  Assert.assertTrue("The color of the video should be green",
      getPage().similarColor(CHROME_VIDEOTEST_COLOR));

  // Release Media Pipeline
  mp.release();
}
 
Example #21
Source File: WebRtcFakeMediaTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebRtcLoopback() throws Exception {

  // Media Pipeline
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(mp).build();
  webRtcEndpoint.connect(webRtcEndpoint);

  final CountDownLatch flowingLatch = new CountDownLatch(1);
  webRtcEndpoint
      .addMediaFlowInStateChangeListener(new EventListener<MediaFlowInStateChangeEvent>() {

        @Override
        public void onEvent(MediaFlowInStateChangeEvent event) {
          if (event.getState().equals(MediaFlowState.FLOWING)) {
            flowingLatch.countDown();
          }
        }
      });

  // Start WebRTC and wait for playing event
  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEndpoint, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_RCV);

  Assert.assertTrue("Not received FLOWING IN event in webRtcEp: " + WebRtcChannel.AUDIO_AND_VIDEO,
      flowingLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  Assert.assertTrue(
      "Not received media (timeout waiting playing event): " + WebRtcChannel.AUDIO_AND_VIDEO,
      getPage().waitForEvent("playing"));

  // Guard time to play the video
  waitSeconds(PLAYTIME);

  // Assertions
  double currentTime = getPage().getCurrentTime();
  Assert.assertTrue(
      "Error in play time (expected: " + PLAYTIME + " sec, real: " + currentTime + " sec)",
      getPage().compare(PLAYTIME, currentTime));

  // Release Media Pipeline
  mp.release();
}
 
Example #22
Source File: DispatcherOneToManyPlayerTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testDispatcherOneToManyPlayer() throws Exception {
  MediaPipeline mp = kurentoClient.createMediaPipeline();

  PlayerEndpoint playerEp =
      new PlayerEndpoint.Builder(mp, "http://" + getTestFilesHttpPath() + "/video/30sec/red.webm")
          .build();
  PlayerEndpoint playerEp2 = new PlayerEndpoint.Builder(mp,
      "http://" + getTestFilesHttpPath() + "/video/30sec/blue.webm").build();
  WebRtcEndpoint webRtcEp1 = new WebRtcEndpoint.Builder(mp).build();
  WebRtcEndpoint webRtcEp2 = new WebRtcEndpoint.Builder(mp).build();
  WebRtcEndpoint webRtcEp3 = new WebRtcEndpoint.Builder(mp).build();

  DispatcherOneToMany dispatcherOneToMany = new DispatcherOneToMany.Builder(mp).build();
  HubPort hubPort1 = new HubPort.Builder(dispatcherOneToMany).build();
  HubPort hubPort2 = new HubPort.Builder(dispatcherOneToMany).build();
  HubPort hubPort3 = new HubPort.Builder(dispatcherOneToMany).build();
  HubPort hubPort4 = new HubPort.Builder(dispatcherOneToMany).build();
  HubPort hubPort5 = new HubPort.Builder(dispatcherOneToMany).build();

  playerEp.connect(hubPort1);
  playerEp2.connect(hubPort2);
  hubPort3.connect(webRtcEp1);
  hubPort4.connect(webRtcEp2);
  hubPort5.connect(webRtcEp3);
  dispatcherOneToMany.setSource(hubPort1);

  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp2.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });

  // Test execution
  getPage(BROWSER1).subscribeEvents("playing");
  getPage(BROWSER1).initWebRtc(webRtcEp2, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);

  getPage(BROWSER2).subscribeEvents("playing");
  getPage(BROWSER2).initWebRtc(webRtcEp1, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);

  getPage(BROWSER3).subscribeEvents("playing");
  getPage(BROWSER3).initWebRtc(webRtcEp3, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);

  playerEp.play();

  // Assertions
  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER1).waitForEvent("playing"));
  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER2).waitForEvent("playing"));
  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER3).waitForEvent("playing"));

  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER1).similarColor(Color.RED));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER2).similarColor(Color.RED));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER3).similarColor(Color.RED));

  Thread.sleep(3000);
  playerEp2.play();
  dispatcherOneToMany.setSource(hubPort2);

  Assert.assertTrue("The color of the video should be blue",
      getPage(BROWSER1).similarColor(Color.BLUE));
  Assert.assertTrue("The color of the video should be blue",
      getPage(BROWSER2).similarColor(Color.BLUE));
  Assert.assertTrue("The color of the video should be blue",
      getPage(BROWSER3).similarColor(Color.BLUE));

  Thread.sleep(3000);
  dispatcherOneToMany.setSource(hubPort1);

  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER1).similarColor(Color.RED));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER2).similarColor(Color.RED));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER3).similarColor(Color.RED));

  Thread.sleep(3000);

  dispatcherOneToMany.setSource(hubPort2);

  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER1).similarColor(Color.BLUE));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER2).similarColor(Color.BLUE));
  Assert.assertTrue("The color of the video should be red",
      getPage(BROWSER3).similarColor(Color.BLUE));

  Thread.sleep(3000);

  Assert.assertTrue("Not received EOS event in player",
      eosLatch.await(TIMEOUT_EOS, TimeUnit.SECONDS));
}
 
Example #23
Source File: RecorderStopTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension) throws Exception {

  final CountDownLatch recorderLatch = new CountDownLatch(1);

  // Media Pipeline #1
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  PlayerEndpoint playerEp =
      new PlayerEndpoint.Builder(mp, getPlayerUrl("/video/10sec/green.webm")).build();
  WebRtcEndpoint webRtcEp1 = new WebRtcEndpoint.Builder(mp).build();

  String recordingFile = getRecordUrl(extension);

  final RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();
  playerEp.connect(webRtcEp1);

  playerEp.connect(recorderEp);

  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });

  // Test execution #1. Play the video while it is recorded
  launchBrowser(mp, webRtcEp1, playerEp, recorderEp, expectedVideoCodec, expectedAudioCodec,
      recordingFile, EXPECTED_COLOR, 0, 0, PLAYTIME);

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  executor.schedule(new Runnable() {

    @Override
    public void run() {
      recorderEp.stopAndWait(new Continuation<Void>() {

        @Override
        public void onSuccess(Void result) throws Exception {
          recorderLatch.countDown();
        }

        @Override
        public void onError(Throwable cause) throws Exception {
          recorderLatch.countDown();
        }
      });
    }
  }, PLAYTIME / 2, TimeUnit.SECONDS);

  // Wait for EOS
  Assert.assertTrue("No EOS event", eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  // Release Media Pipeline #1
  mp.release();

  // Wait until file exists
  waitForFileExists(recordingFile);

  // Reloading browser
  getPage().reload();

  // Media Pipeline #2
  MediaPipeline mp2 = kurentoClient.createMediaPipeline();
  PlayerEndpoint playerEp2 = new PlayerEndpoint.Builder(mp2, recordingFile).build();
  WebRtcEndpoint webRtcEp2 = new WebRtcEndpoint.Builder(mp2).build();
  playerEp2.connect(webRtcEp2);

  // Playing the recording
  launchBrowser(null, webRtcEp2, playerEp2, null, expectedVideoCodec, expectedAudioCodec,
      recordingFile, EXPECTED_COLOR, 0, 0, PLAYTIME / 2);

  // Release Media Pipeline #2
  mp2.release();

  executor.shutdown();

  success = true;
}
 
Example #24
Source File: RecorderSwitchPlayerWithPassThroughTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension, String[] mediaUrls, Color[] expectedColors)
        throws Exception {

  MediaPipeline mp = kurentoClient.createMediaPipeline();
  final CountDownLatch errorPipelinelatch = new CountDownLatch(1);

  mp.addErrorListener(new EventListener<ErrorEvent>() {

    @Override
    public void onEvent(ErrorEvent event) {
      msgError = "Description:" + event.getDescription() + "; Error code:" + event.getType();
      errorPipelinelatch.countDown();
    }
  });

  int numPlayers = mediaUrls.length;
  PlayerEndpoint[] players = new PlayerEndpoint[numPlayers];

  for (int i = 0; i < numPlayers; i++) {
    players[i] = new PlayerEndpoint.Builder(mp, mediaUrls[i]).build();
  }

  WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(mp).build();

  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();

  PassThrough passThrough = new PassThrough.Builder(mp).build();

  passThrough.connect(recorderEp);

  // Test execution
  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);

  final CountDownLatch recorderLatch = new CountDownLatch(1);

  boolean startRecord = false;
  for (int i = 0; i < numPlayers; i++) {
    players[i].connect(webRtcEp);
    players[i].connect(passThrough);
    players[i].play();

    if (!startRecord) {

      Assert.assertTrue("Not received media (timeout waiting playing event)",
          getPage().waitForEvent("playing"));
      recorderEp.record();
      startRecord = true;
    }

    waitSeconds(PLAYTIME / numPlayers);
  }

  saveGstreamerDot(mp);
  recorderEp.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  mp.release();

  Assert.assertTrue(msgError, errorPipelinelatch.getCount() == 1);

  // Reloading browser
  getPage().reload();

  checkRecordingFile(recordingFile, "browser", expectedColors, PLAYTIME, expectedVideoCodec,
      expectedAudioCodec);
  success = true;
}
 
Example #25
Source File: BaseRecorder.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
protected void checkRecordingFile(String recordingFile, String browserName,
    Color[] expectedColors, long playTime, String expectedVideoCodec, String expectedAudioCodec)
        throws InterruptedException {

  // Checking continuity of the audio
  Timer gettingStats = new Timer();
  final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1);

  waitForFileExists(recordingFile);

  MediaPipeline mp = kurentoClient.createMediaPipeline();
  PlayerEndpoint playerEp = new PlayerEndpoint.Builder(mp, recordingFile).build();
  WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(mp).build();
  playerEp.connect(webRtcEp);

  // Playing the recording
  WebRtcTestPage checkPage = getPage(browserName);
  checkPage.setThresholdTime(checkPage.getThresholdTime() * 2);
  checkPage.subscribeEvents("playing");
  checkPage.initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });
  playerEp.play();

  // Assertions in recording
  final String messageAppend = "[played file with media pipeline]";
  Assert.assertTrue(
      "Not received media in the recording (timeout waiting playing event) " + messageAppend,
      checkPage.waitForEvent("playing"));

  checkPage.activatePeerConnectionInboundStats("webRtcPeer.peerConnection");

  gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, checkPage), 100, 200);

  for (Color color : expectedColors) {
    Assert.assertTrue("The color of the recorded video should be " + color + " " + messageAppend,
        checkPage.similarColorAt(color, 50, 50));
  }
  Assert.assertTrue("Not received EOS event in player",
      eosLatch.await(checkPage.getTimeout(), TimeUnit.SECONDS));

  gettingStats.cancel();

  double currentTime = checkPage.getCurrentTime();
  Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime
      + " sec, real: " + currentTime + " sec) " + messageAppend,
      checkPage.compare(playTime, currentTime));

  Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets",
      errorContinuityAudiolatch.getCount() == 1);

  AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec);
  AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime),
      TimeUnit.SECONDS.toMillis(checkPage.getThresholdTime()));

  mp.release();
}
 
Example #26
Source File: RecorderPlayerDisconnectTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension) throws Exception {

  final CountDownLatch recorderLatch = new CountDownLatch(1);

  // Media Pipeline #1
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  PlayerEndpoint playerGreen =
      new PlayerEndpoint.Builder(mp, getPlayerUrl("/video/10sec/green.webm")).build();

  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();

  playerGreen.play();
  recorderEp.record();
  for (int i = 0; i < NUM_SWAPS; i++) {
    if (i % 2 == 0) {
      playerGreen.connect(recorderEp);
    } else {
      playerGreen.disconnect(recorderEp);
    }

    Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / NUM_SWAPS);
  }

  // Release Media Pipeline #1
  saveGstreamerDot(mp);

  recorderEp.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  mp.release();

  // Wait until file exists
  waitForFileExists(recordingFile);

  // Reloading browser
  getPage().reload();

  // Media Pipeline #2
  MediaPipeline mp2 = kurentoClient.createMediaPipeline();
  PlayerEndpoint playerEp2 = new PlayerEndpoint.Builder(mp2, recordingFile).build();
  WebRtcEndpoint webRtcEp2 = new WebRtcEndpoint.Builder(mp2).build();
  playerEp2.connect(webRtcEp2);

  // Playing the recording
  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEp2, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp2.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });
  playerEp2.play();

  // Assertions in recording
  final String messageAppend = "[played file with media pipeline]";
  final int playtime = PLAYTIME;

  Assert.assertTrue(
      "Not received media in the recording (timeout waiting playing event) " + messageAppend,
      getPage().waitForEvent("playing"));
  for (Color color : EXPECTED_COLORS) {
    Assert.assertTrue("The color of the recorded video should be " + color + " " + messageAppend,
        getPage().similarColor(color));
  }
  Assert.assertTrue("Not received EOS event in player",
      eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  double currentTime = getPage().getCurrentTime();
  Assert.assertTrue("Error in play time in the recorded video (expected: " + playtime
      + " sec, real: " + currentTime + " sec) " + messageAppend,
      getPage().compare(playtime, currentTime));

  AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec);
  AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playtime),
      TimeUnit.SECONDS.toMillis(getPage().getThresholdTime()));

  // Release Media Pipeline #2
  mp2.release();

  success = true;
}
 
Example #27
Source File: BaseRecorder.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
protected void launchBrowser(MediaPipeline mp, WebRtcEndpoint webRtcEp, PlayerEndpoint playerEp,
    RecorderEndpoint recorderEp, String expectedVideoCodec, String expectedAudioCodec,
    String recordingFile, Color expectedColor, int xColor, int yColor, int playTime)
        throws InterruptedException {

  Timer gettingStats = new Timer();
  final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1);

  getPage().subscribeEvents("playing");
  getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
  playerEp.play();
  final CountDownLatch eosLatch = new CountDownLatch(1);
  playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
    @Override
    public void onEvent(EndOfStreamEvent event) {
      eosLatch.countDown();
    }
  });

  if (recorderEp != null) {
    recorderEp.record();
  }

  // Assertions
  String inRecording = recorderEp == null ? " in the recording" : "";

  Assert.assertTrue("Not received media (timeout waiting playing event)" + inRecording,
      getPage().waitForEvent("playing"));

  if (recorderEp == null) {
    // Checking continuity of the audio
    getPage().activatePeerConnectionInboundStats("webRtcPeer.peerConnection");

    gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, getPage()), 100,
        200);
  }

  Assert.assertTrue(
      "Color at coordinates " + xColor + "," + yColor + " must be " + expectedColor + inRecording,
      getPage().similarColorAt(expectedColor, xColor, yColor));
  Assert.assertTrue("Not received EOS event in player" + inRecording,
      eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

  final CountDownLatch recorderLatch = new CountDownLatch(1);
  if (recorderEp != null) {

    saveGstreamerDot(mp);

    recorderEp.stopAndWait(new Continuation<Void>() {

      @Override
      public void onSuccess(Void result) throws Exception {
        recorderLatch.countDown();
      }

      @Override
      public void onError(Throwable cause) throws Exception {
        recorderLatch.countDown();
      }
    });

    Assert.assertTrue("Not stop properly",
        recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));

    // Wait until file exists
    waitForFileExists(recordingFile);

    AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec);
    AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime),
        TimeUnit.SECONDS.toMillis(getPage().getThresholdTime()));

  } else {
    gettingStats.cancel();
    getPage().stopPeerConnectionInboundStats("webRtcPeer.peerConnection");
    double currentTime = getPage().getCurrentTime();
    Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime
        + " sec, real: " + currentTime + " sec) " + inRecording,
        getPage().compare(playTime, currentTime));

    if (recorderEp == null) {
      Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets",
          errorContinuityAudiolatch.getCount() == 1);
    }

  }
}
 
Example #28
Source File: RecorderSwitchWebRtcWebRtcAndPlayerTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension) throws Exception {
  // Media Pipeline #1
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  final CountDownLatch errorPipelinelatch = new CountDownLatch(1);

  mp.addErrorListener(new EventListener<ErrorEvent>() {

    @Override
    public void onEvent(ErrorEvent event) {
      msgError = "Description:" + event.getDescription() + "; Error code:" + event.getType();
      errorPipelinelatch.countDown();
    }
  });

  WebRtcEndpoint webRtcEpRed = new WebRtcEndpoint.Builder(mp).build();
  WebRtcEndpoint webRtcEpGreen = new WebRtcEndpoint.Builder(mp).build();

  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();

  // Test execution
  getPage(BROWSER1).subscribeLocalEvents("playing");
  long startWebrtc = System.currentTimeMillis();
  getPage(BROWSER1).initWebRtc(webRtcEpRed, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_ONLY);

  webRtcEpRed.connect(recorderEp);
  recorderEp.record();

  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER1).waitForEvent("playing"));
  long webrtcRedConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  getPage(BROWSER2).subscribeLocalEvents("playing");
  startWebrtc = System.currentTimeMillis();
  getPage(BROWSER2).initWebRtc(webRtcEpGreen, WebRtcChannel.AUDIO_AND_VIDEO,
      WebRtcMode.SEND_ONLY);

  // green
  webRtcEpGreen.connect(recorderEp);

  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER2).waitForEvent("playing"));
  long webrtcGreenConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  webRtcEpRed.connect(recorderEp);

  startWebrtc = System.currentTimeMillis();
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  // Release Media Pipeline #1
  saveGstreamerDot(mp);
  final CountDownLatch recorderLatch = new CountDownLatch(1);
  recorderEp.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage(BROWSER2).getTimeout(), TimeUnit.SECONDS));
  mp.release();

  Assert.assertTrue(msgError, errorPipelinelatch.getCount() == 1);

  final long playtime = PLAYTIME + TimeUnit.MILLISECONDS
      .toSeconds((2 * webrtcRedConnectionTime) + webrtcGreenConnectionTime);

  checkRecordingFile(recordingFile, BROWSER3, EXPECTED_COLORS, playtime, expectedVideoCodec,
      expectedAudioCodec);
  success = true;
}
 
Example #29
Source File: RecorderSwitchWebRtcWebRtcAndPlayerTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTestWithPlayer(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension, String mediaUrlPlayer) throws Exception {
  // Media Pipeline #1
  getPage(BROWSER2).close();
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  final CountDownLatch errorPipelinelatch = new CountDownLatch(1);

  mp.addErrorListener(new EventListener<ErrorEvent>() {

    @Override
    public void onEvent(ErrorEvent event) {
      msgError = "Description:" + event.getDescription() + "; Error code:" + event.getType();
      errorPipelinelatch.countDown();
    }
  });

  WebRtcEndpoint webRtcEpRed = new WebRtcEndpoint.Builder(mp).build();
  PlayerEndpoint playerEp = new PlayerEndpoint.Builder(mp, mediaUrlPlayer).build();

  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();

  // Test execution
  getPage(BROWSER1).subscribeLocalEvents("playing");
  long startWebrtc = System.currentTimeMillis();
  getPage(BROWSER1).initWebRtc(webRtcEpRed, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_ONLY);

  webRtcEpRed.connect(recorderEp);
  recorderEp.record();

  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER1).waitForEvent("playing"));
  long webrtcRedConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  startWebrtc = System.currentTimeMillis();

  playerEp.play();
  playerEp.connect(recorderEp);
  long playerEpConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  webRtcEpRed.connect(recorderEp);
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  // Release Media Pipeline #1
  saveGstreamerDot(mp);

  final CountDownLatch recorderLatch = new CountDownLatch(1);
  recorderEp.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage(BROWSER1).getTimeout(), TimeUnit.SECONDS));
  mp.release();

  Assert.assertTrue(msgError, errorPipelinelatch.getCount() == 1);

  final long playtime = PLAYTIME
      + TimeUnit.MILLISECONDS.toSeconds((2 * webrtcRedConnectionTime) + playerEpConnectionTime);

  checkRecordingFile(recordingFile, BROWSER3, EXPECTED_COLORS, playtime, expectedVideoCodec,
      expectedAudioCodec);
  success = true;
}
 
Example #30
Source File: RecorderSwitchWebRtcWebRtcPlayerWithPassThroughTest.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public void doTest(MediaProfileSpecType mediaProfileSpecType, String expectedVideoCodec,
    String expectedAudioCodec, String extension) throws Exception {
  // Media Pipeline #1
  MediaPipeline mp = kurentoClient.createMediaPipeline();
  final CountDownLatch errorPipelinelatch = new CountDownLatch(1);

  mp.addErrorListener(new EventListener<ErrorEvent>() {

    @Override
    public void onEvent(ErrorEvent event) {
      msgError = "Description:" + event.getDescription() + "; Error code:" + event.getType();
      errorPipelinelatch.countDown();
    }
  });

  WebRtcEndpoint webRtcEpRed = new WebRtcEndpoint.Builder(mp).build();
  WebRtcEndpoint webRtcEpGreen = new WebRtcEndpoint.Builder(mp).build();

  String recordingFile = getRecordUrl(extension);
  RecorderEndpoint recorderEp = new RecorderEndpoint.Builder(mp, recordingFile)
      .withMediaProfile(mediaProfileSpecType).build();

  PassThrough passThrough = new PassThrough.Builder(mp).build();
  passThrough.connect(recorderEp);

  // Test execution
  getPage(BROWSER1).subscribeLocalEvents("playing");
  long startWebrtc = System.currentTimeMillis();
  getPage(BROWSER1).initWebRtc(webRtcEpRed, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_ONLY);

  webRtcEpRed.connect(passThrough);
  recorderEp.record();

  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER1).waitForEvent("playing"));
  long webrtcRedConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  getPage(BROWSER2).subscribeLocalEvents("playing");
  startWebrtc = System.currentTimeMillis();
  getPage(BROWSER2).initWebRtc(webRtcEpGreen, WebRtcChannel.AUDIO_AND_VIDEO,
      WebRtcMode.SEND_ONLY);

  // green
  webRtcEpGreen.connect(passThrough);

  Assert.assertTrue("Not received media (timeout waiting playing event)",
      getPage(BROWSER2).waitForEvent("playing"));
  long webrtcGreenConnectionTime = System.currentTimeMillis() - startWebrtc;
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  webRtcEpRed.connect(passThrough);
  startWebrtc = System.currentTimeMillis();
  Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME) / N_PLAYER);

  // Release Media Pipeline #1
  saveGstreamerDot(mp);
  final CountDownLatch recorderLatch = new CountDownLatch(1);
  recorderEp.stopAndWait(new Continuation<Void>() {

    @Override
    public void onSuccess(Void result) throws Exception {
      recorderLatch.countDown();
    }

    @Override
    public void onError(Throwable cause) throws Exception {
      recorderLatch.countDown();
    }
  });

  Assert.assertTrue("Not stop properly",
      recorderLatch.await(getPage(BROWSER2).getTimeout(), TimeUnit.SECONDS));
  mp.release();

  Assert.assertTrue(msgError, errorPipelinelatch.getCount() == 1);

  final long playtime = PLAYTIME + TimeUnit.MILLISECONDS
      .toSeconds((2 * webrtcRedConnectionTime) + webrtcGreenConnectionTime);

  checkRecordingFile(recordingFile, BROWSER3, EXPECTED_COLORS, playtime, expectedVideoCodec,
      expectedAudioCodec);
  success = true;
}