Java http Streaming Video with VLCJ - Your input can't be opened - java

I'm trying to write a http video streaming application with Java using VLCJ library but I have problem "your input can't be opened".
OS: Windows10 x64
My source code: https://github.com/caprica/vlcj/blob/master/src/test/java/uk/co/caprica/vlcj/test/streaming/StreamHttp.java
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.headless.HeadlessMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import uk.co.caprica.vlcj.runtime.x.LibXUtil;
import java.io.File;
/**
* An example of how to stream a media file over HTTP.
* <p>
* The client specifies an MRL of <code>http://127.0.0.1:5555</code>
*/
public class VideoStream extends VlcjTest{
public static void main(String[] args) throws Exception {
System.setProperty("VLC_PLUGIN_PATH", "D:\\Program Files\\VideoLAN\\VLC\\plugins");
File vlcInstallPath = new File("D:\\Program Files\\VideoLAN\\VLC");
NativeLibrary.addSearchPath(
RuntimeUtil.getLibVlcLibraryName(), vlcInstallPath.getAbsolutePath());
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
LibXUtil.initialise();
String media = "D://demo.mp4";
String options = formatHttpStream("127.0.0.1", 5555);
System.out.println("Streaming '" + media + "' to '" + options + "'");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
mediaPlayer.playMedia(media, options);
// Don't exit
Thread.currentThread().join();
}
private static String formatHttpStream(String serverAddress, int serverPort) {
StringBuilder sb = new StringBuilder(60);
sb.append(":sout=#duplicate{dst=std{access=http,mux=ts,");
sb.append("dst=");
sb.append(serverAddress);
sb.append(':');
sb.append(serverPort);
sb.append("}}");
return sb.toString();
}
}
and result:
[000000001a948be0] access_output_http access out: Consider passing --http-host=IP on the command line instead.
[000000001aa2def0] core input error: open of `D://demo.mp4' failed
[000000001aa2def0] core input error: Your input can't be opened
[000000001aa2def0] core input error: VLC is unable to open the MRL 'D://demo.mp4'. Check the log for details.

The issue is in
String media = "D://demo.mp4";
as suggested by the comment. With // after the D: it will be considered a protocol name.
One of the following variants should work for you:
String media = "D:/demo.mp4";
provided that playMedia supports local file paths. Or
String media = new File("D:/demo.mp4").toURI().toURL();
if it requires a URL string.

Related

How can I launch a UFT Mobile test script remotely from a java application?

I'm developing a java application that will be used to launch remotely the UFT Mobile scripts, on related server, download the test result from it and then analyze the report in order to save the results on a specific database.
I'm writing this post in order to ask a help about it.
The application will have the following steps:
A file properties where I read the name of scripts and some properties needed for application
A class that will be used to connect to the Mobile Center of UFT Mobile in order to install through Mobile Center API the application that will be under the test
A class that will connect to the server and start the execution of test script of application installed on step 2
Download the test result/logs in order to analyze the report and save the result on database
Step 2 (UFTLabUtils is a class of API related to Mobile Center):
package uft;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class UploadFile {
public static boolean uploadFile(Properties myPropertiesFile) throws IOException {
final String MC_SERVER = myPropertiesFile.getProperty("CLOUD_NAME").toLowerCase();
final String USERNAME = myPropertiesFile.getProperty("USERNAME");
final String PASSWORD = myPropertiesFile.getProperty("PASSWORD");
final String PACKAGE = myPropertiesFile.getProperty("PACKAGE");
final String VERSION = myPropertiesFile.getProperty("VERSION");
final String DEVICE_ID = myPropertiesFile.getProperty("DEVICE_ID");
final Boolean STRUMENTED = true;
try {
UFTLabUtils client = new UFTLabUtils(USERNAME, PASSWORD, MC_SERVER);
client.login(USERNAME, PASSWORD);
client.installApp(PACKAGE, VERSION, DEVICE_ID, STRUMENTED);
client.logout();
return true;
}catch(Exception e) {
System.err.println("Si è verificato un errore nella uploadFile: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
return false;
}
}
}
The problem is on the step 3, where I cannot find a way to execute the script saved of UFT Mobile Server.
I'm looking on internet and I found some snippet code like this that I customized:
package uft;
import java.util.HashMap;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONObject;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
public class StartExecution {
#SuppressWarnings("unused")
public static String startExecution(Properties myPropertiesFile) {
final String MC_SERVER = myPropertiesFile.getProperty("CLOUD_NAME");
final String MC_SERVER_CLIENT_ID = myPropertiesFile.getProperty("MC_SERVER_CLIENT_ID");
final String MC_SERVER_CLIENT_SECRET = myPropertiesFile.getProperty("MC_SERVER_CLIENT_SECRET");
final String MC_SERVER_TENANT_ID = myPropertiesFile.getProperty("MC_SERVER_TENANT_ID");
final String MC_SERVER_WORKSPACE_NAME = myPropertiesFile.getProperty("MC_SERVER_WORKSPACE_NAME");
try {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("oauthClientId", MC_SERVER_CLIENT_ID);
capabilities.setCapability("oauthClientSecret", MC_SERVER_CLIENT_SECRET);
capabilities.setCapability("tenantId", MC_SERVER_TENANT_ID);
capabilities.setCapability("mcWorkspaceName", MC_SERVER_WORKSPACE_NAME);
switch (myPropertiesFile.getProperty("OS").toUpperCase()) {
case "ANDROID":
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appPackage", "com.Advantage.aShopping");
capabilities.setCapability("appActivity", "com.Advantage.aShopping.SplashActivity");
AndroidDriver wd = new AndroidDriver(new URL(MC_SERVER + "/wd/hub"), capabilities);
wd.executeScript(MC_SERVER_WORKSPACE_NAME, null);
HashMap<String, String> encoding= new HashMap<String, String>();
encoding.put("encoding", "UTF-8");
String logFileContents = (String) wd.executeScript("mc-wd: downloadLogs", encoding);
case "IOS":
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("bundleId", "com.Advantage.aShopping");
IOSDriver wd2 = new IOSDriver(new URL(MC_SERVER + "/wd/hub"), capabilities);
wd2.executeScript(MC_SERVER_WORKSPACE_NAME, null);
HashMap<String, String> encoding2= new HashMap<String, String>();
encoding2.put("encoding", "UTF-8");
String logFileContents2 = (String) wd2.executeScript("mc-wd: downloadLogs", encoding2);
}
return null;
}catch(Exception e) {
System.out.println("Si è verificato un problema nella startExecution: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
return null;
}
}
All desired capabilities are read from external, in particular from the file properties that is in input to the java application.
The question is: after the connection to the mobile center, in particular, to the hub (wd/hub), how can I start and launch a test script that is saved on server (not in local)?
Furthermore, I looked the documentation about the method 'executeScript', but it is used to run a JavaScript code/command.
UPDATE: I also found this snippet:
public static void main(String args[]) {
try {
PrintStream out = new PrintStream(new FileOutputStream("LaunchQTP.vbs"));
out.println("Set qtApp = CreateObject(\"QuickTest.Application\")");
out.println("qtApp.Launch");
out.println("qtApp.Visible = True");
out.close();
Process p = Runtime.getRuntime().exec("cscript LaunchQTP.vbs");
p.waitFor();
out.println(p.exitValue());
} catch (Exception err) {
err.printStackTrace();
}
}
that seems to be used for launch a UFT scripts but on local machine. Could it be used also for remotely server? In this case how can i connect to the server and launch the script?
Thanks for supporting!

SpeechClient not importing in intellij

I'm trying this: https://cloud.google.com/speech-to-text/docs/reference/libraries#client-libraries-install-java
But the import import com.google.cloud.speech.v1.SpeechClient; shows error. Rest of the classes under the cloud speech api are importing just fine.
I have created the GCP Service account and downloaded the json file for my project, and I even set my google credential to that json file using powershell.
// Imports the Google Cloud client library
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class QuickstartSample {
/**
* Demonstrates using the Speech API to transcribe an audio file.
*/
public static void main(String... args) throws Exception {
// Instantiates a client
try (SpeechClient speechClient = SpeechClient.create()) {
// The path to the audio file to transcribe
String fileName = "./resources/audio.raw";
// Reads the audio file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);
// Builds the sync recognize request
RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRateHertz(16000)
.setLanguageCode("en-US")
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setContent(audioBytes)
.build();
// Performs speech recognition on the audio file
RecognizeResponse response = speechClient.recognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();
for (SpeechRecognitionResult result : results) {
// There can be several alternative transcripts for a given chunk of speech. Just use the
// first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
}
}

google cloud speech SpeechClient not found

I use intellij idea, i have included the google cloud speech api but he dont finde the SpeechClient (https://image.prntscr.com/image/3S9bjQWgRdGGB1olHihxkA.png) (https://image.prntscr.com/image/RVspqW2-QuqD2mytN3V8Qw.png) why? I dont now why the java code not found this data in google documenten is this code working its the example code.
https://cloud.google.com/speech-to-text/docs/reference/libraries#client-libraries-usage-java
https://image.prntscr.com/image/fFVm7P7SRheGYWCqTvdDAQ.png
package de.****.test;
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class main {
/**
* Demonstrates using the Speech API to transcribe an audio file.
*/
public static void main(String... args) throws Exception {
// Instantiates a client
try (SpeechClient speechClient = SpeechClient.create()) {
// The path to the audio file to transcribe
String fileName = "./resources/audio.raw";
// Reads the audio file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);
// Builds the sync recognize request
RecognitionConfig config = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRateHertz(16000)
.setLanguageCode("en-US")
.build();
RecognitionAudio audio = RecognitionAudio.newBuilder()
.setContent(audioBytes)
.build();
// Performs speech recognition on the audio file
RecognizeResponse response = speechClient.recognize(config, audio);
List<SpeechRecognitionResult> results = response.getResultsList();
for (SpeechRecognitionResult result : results) {
// There can be several alternative transcripts for a given chunk of speech. Just use the
// first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
}
}

File.setTitle method equivalent in Google Drive API v3

Here is an official example:
package com.google.api.services.samples.drive.cmdline;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.media.MediaHttpDownloader;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Collections;
/**
* A sample application that runs multiple requests against the Drive API. The requests this sample
* makes are:
* <ul>
* <li>Does a resumable media upload</li>
* <li>Updates the uploaded file by renaming it</li>
* <li>Does a resumable media download</li>
* <li>Does a direct media upload</li>
* <li>Does a direct media download</li>
* </ul>
*
* #author rmistry#google.com (Ravi Mistry)
*/
public class DriveSample {
/**
* Be sure to specify the name of your application. If the application name is {#code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "";
private static final String UPLOAD_FILE_PATH = "Enter File Path";
private static final String DIR_FOR_DOWNLOADS = "Enter Download Directory";
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/drive_sample");
/**
* Global instance of the {#link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global Drive API client. */
private static Drive drive;
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(DriveSample.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=drive "
+ "into drive-cmdline-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args) {
Preconditions.checkArgument(
!UPLOAD_FILE_PATH.startsWith("Enter ") && !DIR_FOR_DOWNLOADS.startsWith("Enter "),
"Please enter the upload file path and download directory in %s", DriveSample.class);
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up the global Drive instance
drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(
APPLICATION_NAME).build();
// run commands
View.header1("Starting Resumable Media Upload");
File uploadedFile = uploadFile(false);
View.header1("Updating Uploaded File Name");
File updatedFile = updateFileWithTestSuffix(uploadedFile.getId());
View.header1("Starting Resumable Media Download");
downloadFile(false, updatedFile);
View.header1("Starting Simple Media Upload");
uploadedFile = uploadFile(true);
View.header1("Starting Simple Media Download");
downloadFile(true, uploadedFile);
View.header1("Success!");
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
FileContent mediaContent = new FileContent("image/jpeg", UPLOAD_FILE);
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
/** Updates the name of the uploaded file to have a "drivetest-" prefix. */
private static File updateFileWithTestSuffix(String id) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle("drivetest-" + UPLOAD_FILE.getName());
Drive.Files.Update update = drive.files().update(id, fileMetadata);
return update.execute();
}
/** Downloads a file using either resumable or direct media download. */
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
}
}
One problem is that the setTitle method does not exist any more in the latest Java API. How do I set the title of a file now?
Some changes in above code
setTitle has been changed into setName
Drive.Files.Insert -> Drive.Files.Create
drive.files().insert(fileMetadata, mediaContent); -> drive.files().create(fileMetadata, mediaContent)
getTitle() -> getName()
uploadedFile.getDownloadUrl() -> uploadedFile.getWebViewLink()
Following code has all new Method names.
change last part of code and paste
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setName(UPLOAD_FILE.getName());
FileContent mediaContent = new FileContent("image/jpeg", UPLOAD_FILE);
Drive.Files.Create insert = drive.files().create(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
/** Updates the name of the uploaded file to have a "drivetest-" prefix. */
private static File updateFileWithTestSuffix(String id) throws IOException {
File fileMetadata = new File();
fileMetadata.setName("drivetest-" + UPLOAD_FILE.getName());
Drive.Files.Update update = drive.files().update(id, fileMetadata);
return update.execute();
}
/** Downloads a file using either resumable or direct media download. */
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getName()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getWebViewLink()), out);
}
setTitle has been changed into setName in v3.

Java send Live Video InputStream to Red5 Media Server

I have an InputStream from a Socket in Java.
The InputStream is a H.264 video live stream. I would like to send this Video InputStream to a red5 Media Server, so that other clients can watch it.
I found this example
package com.ryong21.example.publisher;import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.red5.server.messaging.IMessage;
import org.red5.server.stream.message.RTMPMessage;
import org.red5.server.stream.provider.FileProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher {
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher.class);
String publishName = "test";
String localFile = "2.mp3";
String host = "rtmpxn.91kge.com";
int port = 1935;
String app = "live";
IMessage msg = null;
int timestamp = 0;
int lastTS = 0;
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while(client.getState() != PublishClient.PUBLISHED){
Thread.sleep(500);
}
FileProvider fp = new FileProvider(new File(localFile));
Date begin = new Date();
log.debug(begin.toString());
while(true){
msg = fp.pullMessage(null);
if(msg == null){
log.debug("done!");
break;
}
timestamp = ((RTMPMessage)msg).getBody().getTimestamp();
Thread.sleep(timestamp - lastTS);
lastTS = timestamp;
client.pushMessage( msg);
}
Date end = new Date();
log.debug(end.toString());
client.stop();
}
}`
My problem is how to use this with a Sockets InputStream, instead of the File used in FileProvider. The InputStream is already in H.264 encoded.
Ok, after digging a little deeper into video streaming, i found out that i ll first have to convert the InputStream to a container format file. Possible container formats are .mp4 or .flv
Having created the container file, i can now publish it to the red5 media server.

Categories