Search in sources :

Example 1 with SoxException

use of org.opencastproject.sox.api.SoxException in project opencast by opencast.

the class SoxServiceRemoteImpl method normalize.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.sox.api.SoxService#normalize(Track, Float)
 */
@Override
public Job normalize(Track sourceAudioTrack, Float targetRmsLevDb) throws MediaPackageException, SoxException {
    HttpPost post = new HttpPost("/normalize");
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("sourceAudioTrack", MediaPackageElementParser.getAsXml(sourceAudioTrack)));
        params.add(new BasicNameValuePair("targetRmsLevDb", targetRmsLevDb.toString()));
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (Exception e) {
        throw new SoxException(e);
    }
    HttpResponse response = null;
    try {
        response = getResponse(post);
        if (response != null) {
            try {
                Job receipt = JobParser.parseJob(response.getEntity().getContent());
                logger.info("Normalizing audio {} on a remote audio processing server", sourceAudioTrack);
                return receipt;
            } catch (Exception e) {
                throw new SoxException("Unable to normalize audio of element '" + sourceAudioTrack + "' using a remote audio processing service", e);
            }
        }
    } finally {
        closeConnection(response);
    }
    throw new SoxException("Unable to normalize audio of element '" + sourceAudioTrack + "' using a remote audio processing service");
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SoxException(org.opencastproject.sox.api.SoxException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Job(org.opencastproject.job.api.Job) SoxException(org.opencastproject.sox.api.SoxException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException)

Example 2 with SoxException

use of org.opencastproject.sox.api.SoxException in project opencast by opencast.

the class SoxServiceImpl method analyze.

protected Option<Track> analyze(Job job, Track audioTrack) throws SoxException {
    if (!audioTrack.hasAudio())
        throw new SoxException("No audio stream available");
    if (audioTrack.hasVideo())
        throw new SoxException("It must not have a video stream");
    try {
        // Get the tracks and make sure they exist
        final File audioFile;
        try {
            audioFile = workspace.get(audioTrack.getURI());
        } catch (NotFoundException e) {
            throw new SoxException("Requested audio track " + audioTrack + " is not found");
        } catch (IOException e) {
            throw new SoxException("Unable to access audio track " + audioTrack);
        }
        logger.info("Analyzing audio track {}", audioTrack.getIdentifier());
        // Do the work
        ArrayList<String> command = new ArrayList<String>();
        command.add(binary);
        command.add(audioFile.getAbsolutePath());
        command.add("-n");
        command.add("remix");
        command.add("-");
        command.add("stats");
        List<String> analyzeResult = launchSoxProcess(command);
        // Add audio metadata and return audio track
        return some(addAudioMetadata(audioTrack, analyzeResult));
    } catch (Exception e) {
        logger.warn("Error analyzing {}: {}", audioTrack, e.getMessage());
        if (e instanceof SoxException) {
            throw (SoxException) e;
        } else {
            throw new SoxException(e);
        }
    }
}
Also used : SoxException(org.opencastproject.sox.api.SoxException) ArrayList(java.util.ArrayList) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) File(java.io.File) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) SoxException(org.opencastproject.sox.api.SoxException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException)

Example 3 with SoxException

use of org.opencastproject.sox.api.SoxException in project opencast by opencast.

the class SoxServiceImpl method normalize.

private Option<Track> normalize(Job job, TrackImpl audioTrack, Float targetRmsLevDb) throws SoxException {
    if (!audioTrack.hasAudio())
        throw new SoxException("No audio stream available");
    if (audioTrack.hasVideo())
        throw new SoxException("It must not have a video stream");
    if (audioTrack.getAudio().size() < 1)
        throw new SoxException("No audio stream metadata available");
    if (audioTrack.getAudio().get(0).getRmsLevDb() == null)
        throw new SoxException("No RMS Lev dB metadata available");
    final String targetTrackId = idBuilder.createNew().toString();
    Float rmsLevDb = audioTrack.getAudio().get(0).getRmsLevDb();
    // Get the tracks and make sure they exist
    final File audioFile;
    try {
        audioFile = workspace.get(audioTrack.getURI());
    } catch (NotFoundException e) {
        throw new SoxException("Requested audio track " + audioTrack + " is not found");
    } catch (IOException e) {
        throw new SoxException("Unable to access audio track " + audioTrack);
    }
    String outDir = audioFile.getAbsoluteFile().getParent();
    String outFileName = FilenameUtils.getBaseName(audioFile.getName()) + "_" + UUID.randomUUID().toString();
    String suffix = "-norm." + FilenameUtils.getExtension(audioFile.getName());
    File normalizedFile = new File(outDir, outFileName + suffix);
    logger.info("Normalizing audio track {} to {}", audioTrack.getIdentifier(), targetTrackId);
    // Do the work
    ArrayList<String> command = new ArrayList<String>();
    command.add(binary);
    command.add(audioFile.getAbsolutePath());
    command.add(normalizedFile.getAbsolutePath());
    command.add("remix");
    command.add("-");
    command.add("gain");
    if (targetRmsLevDb > rmsLevDb)
        command.add("-l");
    command.add(new Float(targetRmsLevDb - rmsLevDb).toString());
    command.add("stats");
    List<String> normalizeResult = launchSoxProcess(command);
    if (normalizedFile.length() == 0)
        throw new SoxException("Normalization failed: Output file is empty!");
    // Put the file in the workspace
    URI returnURL = null;
    InputStream in = null;
    try {
        in = new FileInputStream(normalizedFile);
        returnURL = workspace.putInCollection(COLLECTION, job.getId() + "." + FilenameUtils.getExtension(normalizedFile.getAbsolutePath()), in);
        logger.info("Copied the normalized file to the workspace at {}", returnURL);
        if (normalizedFile.delete()) {
            logger.info("Deleted the local copy of the normalized file at {}", normalizedFile.getAbsolutePath());
        } else {
            logger.warn("Unable to delete the normalized output at {}", normalizedFile);
        }
    } catch (Exception e) {
        throw new SoxException("Unable to put the normalized file into the workspace", e);
    } finally {
        IOUtils.closeQuietly(in);
        FileSupport.deleteQuietly(normalizedFile);
    }
    Track normalizedTrack = (Track) audioTrack.clone();
    normalizedTrack.setURI(returnURL);
    normalizedTrack.setIdentifier(targetTrackId);
    // Add audio metadata and return audio track
    normalizedTrack = addAudioMetadata(normalizedTrack, normalizeResult);
    return some(normalizedTrack);
}
Also used : SoxException(org.opencastproject.sox.api.SoxException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) URI(java.net.URI) FileInputStream(java.io.FileInputStream) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) SoxException(org.opencastproject.sox.api.SoxException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) File(java.io.File) Track(org.opencastproject.mediapackage.Track)

Example 4 with SoxException

use of org.opencastproject.sox.api.SoxException in project opencast by opencast.

the class SoxServiceImpl method launchSoxProcess.

private List<String> launchSoxProcess(List<String> command) throws SoxException {
    Process process = null;
    BufferedReader in = null;
    try {
        logger.info("Start sox process {}", command);
        ProcessBuilder pb = new ProcessBuilder(command);
        // Unfortunately merges but necessary for deadlock prevention
        pb.redirectErrorStream(true);
        process = pb.start();
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        process.waitFor();
        String line = null;
        List<String> stats = new ArrayList<String>();
        while ((line = in.readLine()) != null) {
            logger.info(line);
            stats.add(line);
        }
        if (process.exitValue() != 0)
            throw new SoxException("Sox process failed with error code: " + process.exitValue());
        logger.info("Sox process finished");
        return stats;
    } catch (IOException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } catch (InterruptedException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } finally {
        IoSupport.closeQuietly(in);
    }
}
Also used : SoxException(org.opencastproject.sox.api.SoxException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 5 with SoxException

use of org.opencastproject.sox.api.SoxException in project opencast by opencast.

the class SoxServiceRemoteImpl method analyze.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.sox.api.SoxService#analyze(Track)
 */
@Override
public Job analyze(Track sourceAudioTrack) throws MediaPackageException, SoxException {
    HttpPost post = new HttpPost("/analyze");
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("sourceAudioTrack", MediaPackageElementParser.getAsXml(sourceAudioTrack)));
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (Exception e) {
        throw new SoxException(e);
    }
    HttpResponse response = null;
    try {
        response = getResponse(post);
        if (response != null) {
            try {
                Job receipt = JobParser.parseJob(response.getEntity().getContent());
                logger.info("Analyzing audio {} on a remote analysis server", sourceAudioTrack);
                return receipt;
            } catch (Exception e) {
                throw new SoxException("Unable to analyze audio of element '" + sourceAudioTrack + "' using a remote analysis service", e);
            }
        }
    } finally {
        closeConnection(response);
    }
    throw new SoxException("Unable to analyze audio of element '" + sourceAudioTrack + "' using a remote analysis service");
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SoxException(org.opencastproject.sox.api.SoxException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Job(org.opencastproject.job.api.Job) SoxException(org.opencastproject.sox.api.SoxException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException)

Aggregations

ArrayList (java.util.ArrayList)5 SoxException (org.opencastproject.sox.api.SoxException)5 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)4 IOException (java.io.IOException)3 File (java.io.File)2 HttpResponse (org.apache.http.HttpResponse)2 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)2 HttpPost (org.apache.http.client.methods.HttpPost)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2 Job (org.opencastproject.job.api.Job)2 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)2 NotFoundException (org.opencastproject.util.NotFoundException)2 ConfigurationException (org.osgi.service.cm.ConfigurationException)2 BufferedReader (java.io.BufferedReader)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 URI (java.net.URI)1 Track (org.opencastproject.mediapackage.Track)1