Search in sources :

Example 6 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class DeviceManagerUPnPImpl method initialise.

protected void initialise() {
    plugin_interface = PluginInitializer.getDefaultInterface();
    ta_category = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_CATEGORY);
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            // startup can take a while as adding the upnp listener can sync call back device added and result
            // in device details loading etc
            new AEThread2("DMUPnPAsyncStart", true) {

                @Override
                public void run() {
                    startUp();
                }
            }.start();
        }

        @Override
        public void closedownInitiated() {
        }

        @Override
        public void closedownComplete() {
        }
    });
}
Also used : AEThread2(com.biglybt.core.util.AEThread2) PluginListener(com.biglybt.pif.PluginListener)

Example 7 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class TranscodeProviderVuze method transcode.

@Override
public TranscodeProviderJob transcode(final TranscodeProviderAdapter _adapter, TranscodeProviderAnalysis analysis, boolean direct_input, DiskManagerFileInfo input, TranscodeProfile profile, URL output) throws TranscodeException {
    try {
        PluginInterface av_pi = plugin_interface.getPluginManager().getPluginInterfaceByID("azupnpav");
        if (av_pi == null) {
            throw (new TranscodeException("Media Server plugin not found"));
        }
        final TranscodeProviderJob[] xcode_job = { null };
        URL source_url = null;
        TranscodePipe pipe = null;
        if (direct_input) {
            if (input instanceof DiskManagerFileInfoURL) {
                ((DiskManagerFileInfoURL) input).download();
            }
            if (input.getDownloaded() == input.getLength()) {
                File file = input.getFile();
                if (file.exists() && file.length() == input.getLength()) {
                    source_url = file.toURI().toURL();
                }
            }
            if (source_url == null) {
                manager.log("Failed to use direct input as source file doesn't exist/incomplete");
            }
        }
        if (source_url == null) {
            if (input instanceof DiskManagerFileInfoURL) {
                source_url = ((DiskManagerFileInfoURL) input).getURL();
            } else {
                IPCInterface av_ipc = av_pi.getIPC();
                String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { input });
                if (url_str == null || url_str.length() == 0) {
                    // see if we can use the file directly
                    File source_file = input.getFile();
                    if (source_file.exists()) {
                        pipe = new TranscodePipeFileSource(source_file, new TranscodePipe.errorListener() {

                            @Override
                            public void error(Throwable e) {
                                _adapter.failed(new TranscodeException("File access error", e));
                                if (xcode_job[0] != null) {
                                    xcode_job[0].cancel();
                                }
                            }
                        });
                        source_url = new URL("http://127.0.0.1:" + pipe.getPort() + "/");
                    } else {
                        throw (new TranscodeException("Source file doesn't exist"));
                    }
                } else {
                    source_url = new URL(url_str);
                    pipe = new TranscodePipeStreamSource(source_url.getHost(), source_url.getPort());
                    source_url = UrlUtils.setHost(source_url, "127.0.0.1");
                    source_url = UrlUtils.setPort(source_url, pipe.getPort());
                }
            }
        }
        final TranscodePipe f_pipe = pipe;
        try {
            final IPCInterface ipc = plugin_interface.getIPC();
            final Object context;
            final TranscodeProviderAdapter adapter;
            if (output.getProtocol().equals("tcp")) {
                adapter = _adapter;
                context = ipc.invoke("transcodeToTCP", new Object[] { ((TranscodeProviderAnalysisImpl) analysis).getResult(), source_url, profile.getName(), output.getPort() });
            } else {
                final File file = new File(output.toURI());
                File parent_dir = file.getParentFile();
                if (parent_dir.exists()) {
                    if (!parent_dir.canWrite()) {
                        throw (new TranscodeException("Folder '" + parent_dir.getAbsolutePath() + "' isn't writable"));
                    }
                } else {
                    if (!parent_dir.mkdirs()) {
                        throw (new TranscodeException("Failed to create folder '" + parent_dir.getAbsolutePath() + "'"));
                    }
                }
                adapter = new TranscodeProviderAdapter() {

                    @Override
                    public void updateProgress(int percent, int eta_secs, int width, int height) {
                        _adapter.updateProgress(percent, eta_secs, width, height);
                    }

                    @Override
                    public void streamStats(long connect_rate, long write_speed) {
                        _adapter.streamStats(connect_rate, write_speed);
                    }

                    @Override
                    public void failed(TranscodeException error) {
                        try {
                            file.delete();
                        } finally {
                            _adapter.failed(error);
                        }
                    }

                    @Override
                    public void complete() {
                        _adapter.complete();
                    }
                };
                context = ipc.invoke("transcodeToFile", new Object[] { ((TranscodeProviderAnalysisImpl) analysis).getResult(), source_url, profile.getName(), file });
            }
            new AEThread2("xcodeStatus", true) {

                @Override
                public void run() {
                    try {
                        boolean in_progress = true;
                        while (in_progress) {
                            in_progress = false;
                            if (f_pipe != null) {
                                adapter.streamStats(f_pipe.getConnectionRate(), f_pipe.getWriteSpeed());
                            }
                            try {
                                Map status = (Map) ipc.invoke("getTranscodeStatus", new Object[] { context });
                                long state = (Long) status.get("state");
                                if (state == 0) {
                                    int percent = (Integer) status.get("percent");
                                    Integer i_eta = (Integer) status.get("eta_secs");
                                    int eta = i_eta == null ? -1 : i_eta;
                                    Integer i_width = (Integer) status.get("new_width");
                                    int width = i_width == null ? 0 : i_width;
                                    Integer i_height = (Integer) status.get("new_height");
                                    int height = i_height == null ? 0 : i_height;
                                    adapter.updateProgress(percent, eta, width, height);
                                    if (percent == 100) {
                                        adapter.complete();
                                    } else {
                                        in_progress = true;
                                        Thread.sleep(1000);
                                    }
                                } else if (state == 1) {
                                    adapter.failed(new TranscodeException("Transcode cancelled"));
                                } else {
                                    Boolean perm_fail = (Boolean) status.get("error_is_perm");
                                    TranscodeException error = new TranscodeException("Transcode failed", (Throwable) status.get("error"));
                                    if (perm_fail != null && perm_fail) {
                                        error.setDisableRetry(true);
                                    }
                                    adapter.failed(error);
                                }
                            } catch (Throwable e) {
                                adapter.failed(new TranscodeException("Failed to get status", e));
                            }
                        }
                    } finally {
                        if (f_pipe != null) {
                            f_pipe.destroy();
                        }
                    }
                }
            }.start();
            xcode_job[0] = new TranscodeProviderJob() {

                @Override
                public void pause() {
                    if (f_pipe != null) {
                        f_pipe.pause();
                    }
                }

                @Override
                public void resume() {
                    if (f_pipe != null) {
                        f_pipe.resume();
                    }
                }

                @Override
                public void cancel() {
                    try {
                        ipc.invoke("cancelTranscode", new Object[] { context });
                    } catch (Throwable e) {
                        Debug.printStackTrace(e);
                    }
                }

                @Override
                public void setMaxBytesPerSecond(int max) {
                    if (f_pipe != null) {
                        f_pipe.setMaxBytesPerSecond(max);
                    }
                }
            };
            return (xcode_job[0]);
        } catch (Throwable e) {
            if (pipe != null) {
                pipe.destroy();
            }
            throw (e);
        }
    } catch (TranscodeException e) {
        throw (e);
    } catch (Throwable e) {
        throw (new TranscodeException("transcode failed", e));
    }
}
Also used : PluginInterface(com.biglybt.pif.PluginInterface) DiskManagerFileInfoURL(com.biglybt.core.download.DiskManagerFileInfoURL) URL(java.net.URL) AEThread2(com.biglybt.core.util.AEThread2) DiskManagerFileInfoURL(com.biglybt.core.download.DiskManagerFileInfoURL) File(java.io.File) IPCInterface(com.biglybt.pif.ipc.IPCInterface) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class TranscodeProviderVuze method analyse.

@Override
public TranscodeProviderAnalysis analyse(final TranscodeProviderAdapter _adapter, DiskManagerFileInfo input, TranscodeProfile profile) throws TranscodeException {
    try {
        URL source_url = null;
        File source_file = null;
        long input_length = input.getLength();
        if (input_length > 0 && input_length == input.getDownloaded()) {
            File file = input.getFile();
            if (file.exists() && file.length() == input_length) {
                source_file = file;
            }
        }
        TranscodePipe pipe = null;
        if (source_file == null) {
            if (input instanceof DiskManagerFileInfoURL) {
                source_url = ((DiskManagerFileInfoURL) input).getURL();
            } else {
                for (int i = 0; i < 10; i++) {
                    PluginInterface av_pi = plugin_interface.getPluginManager().getPluginInterfaceByID("azupnpav");
                    if (av_pi == null) {
                        throw (new TranscodeException("Media Server plugin not found"));
                    }
                    IPCInterface av_ipc = av_pi.getIPC();
                    String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { input });
                    if (url_str != null && url_str.length() > 0) {
                        source_url = new URL(url_str);
                        pipe = new TranscodePipeStreamSource(source_url.getHost(), source_url.getPort());
                        source_url = UrlUtils.setHost(source_url, "127.0.0.1");
                        source_url = UrlUtils.setPort(source_url, pipe.getPort());
                    }
                    if (source_url != null) {
                        break;
                    } else {
                        try {
                            Thread.sleep(1000);
                        } catch (Throwable e) {
                            break;
                        }
                    }
                }
            }
        }
        if (source_file == null && source_url == null) {
            throw (new TranscodeException("File doesn't exist"));
        }
        final TranscodePipe f_pipe = pipe;
        try {
            final IPCInterface ipc = plugin_interface.getIPC();
            final Object analysis_context;
            if (source_url != null) {
                analysis_context = ipc.invoke("analyseContent", new Object[] { source_url, profile.getName() });
            } else {
                analysis_context = ipc.invoke("analyseContent", new Object[] { source_file, profile.getName() });
            }
            final Map<String, Object> result = new HashMap<>();
            final TranscodeProviderAnalysisImpl analysis = new TranscodeProviderAnalysisImpl() {

                @Override
                public void cancel() {
                    try {
                        ipc.invoke("cancelAnalysis", new Object[] { analysis_context });
                    } catch (Throwable e) {
                        Debug.printStackTrace(e);
                    }
                }

                @Override
                public boolean foundVideoStream() {
                    return (getLongProperty(PT_VIDEO_WIDTH) > 0);
                }

                @Override
                public boolean getBooleanProperty(int property) {
                    if (property == PT_TRANSCODE_REQUIRED) {
                        return (getBooleanProperty("xcode_required", true));
                    } else {
                        Debug.out("Unknown property: " + property);
                        return (false);
                    }
                }

                @Override
                public void setBooleanProperty(int property, boolean value) {
                    if (property == PT_FORCE_TRANSCODE) {
                        result.put("force_xcode", value);
                    } else {
                        Debug.out("Unknown property: " + property);
                    }
                }

                @Override
                public long getLongProperty(int property) {
                    if (property == PT_DURATION_MILLIS) {
                        long duration = getLongProperty("duration_millis", 0);
                        long audio_duration = getLongProperty("audio_duration_millis", 0);
                        if (duration <= 0 && audio_duration > 0) {
                            duration = audio_duration;
                        }
                        if (audio_duration > 0 && audio_duration < duration) {
                            duration = audio_duration;
                        }
                        return (duration);
                    } else if (property == PT_VIDEO_WIDTH) {
                        return (getLongProperty("video_width", 0));
                    } else if (property == PT_VIDEO_HEIGHT) {
                        return (getLongProperty("video_height", 0));
                    } else if (property == PT_SOURCE_SIZE) {
                        return (getLongProperty("source_size", 0));
                    } else if (property == PT_ESTIMATED_XCODE_SIZE) {
                        return (getLongProperty("estimated_transcoded_size", 0));
                    } else {
                        Debug.out("Unknown property: " + property);
                        return (0);
                    }
                }

                protected boolean getBooleanProperty(String name, boolean def) {
                    Boolean b = (Boolean) result.get(name);
                    if (b != null) {
                        return (b);
                    }
                    return (def);
                }

                protected long getLongProperty(String name, long def) {
                    Long l = (Long) result.get(name);
                    if (l != null) {
                        return (l);
                    }
                    return (def);
                }

                @Override
                public Map<String, Object> getResult() {
                    return (result);
                }
            };
            new AEThread2("analysisStatus", true) {

                @Override
                public void run() {
                    try {
                        while (true) {
                            try {
                                Map status = (Map) ipc.invoke("getAnalysisStatus", new Object[] { analysis_context });
                                long state = (Long) status.get("state");
                                if (state == 0) {
                                    // running
                                    Thread.sleep(50);
                                } else if (state == 1) {
                                    _adapter.failed(new TranscodeException("Analysis cancelled"));
                                    break;
                                } else if (state == 2) {
                                    _adapter.failed(new TranscodeException("Analysis failed", (Throwable) status.get("error")));
                                    break;
                                } else {
                                    result.putAll((Map<String, Object>) status.get("result"));
                                    _adapter.complete();
                                    break;
                                }
                            } catch (Throwable e) {
                                _adapter.failed(new TranscodeException("Failed to get status", e));
                                break;
                            }
                        }
                    } finally {
                        if (f_pipe != null) {
                            f_pipe.destroy();
                        }
                    }
                }
            }.start();
            return (analysis);
        } catch (Throwable e) {
            if (pipe != null) {
                pipe.destroy();
            }
            throw (e);
        }
    } catch (TranscodeException e) {
        throw (e);
    } catch (Throwable e) {
        throw (new TranscodeException("analysis failed", e));
    }
}
Also used : HashMap(java.util.HashMap) PluginInterface(com.biglybt.pif.PluginInterface) DiskManagerFileInfoURL(com.biglybt.core.download.DiskManagerFileInfoURL) URL(java.net.URL) AEThread2(com.biglybt.core.util.AEThread2) DiskManagerFileInfoURL(com.biglybt.core.download.DiskManagerFileInfoURL) File(java.io.File) IPCInterface(com.biglybt.pif.ipc.IPCInterface) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class UpdateCheckInstanceImpl method start.

@Override
public void start() {
    // only run one at a time - easiest approach is just to use a couple of threads
    // to backoff + check for completion
    boolean run_now;
    synchronized (UpdateCheckInstanceImpl.class) {
        if (active_checker == null) {
            // System.out.println( "UCI: starting " + getName());
            active_checker = this;
            run_now = true;
            new AEThread2("UCI:clearer") {

                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                        } catch (Throwable e) {
                        }
                        if (isCompleteOrCancelled()) {
                            boolean done = true;
                            if (completed) {
                                Update[] updates = getUpdates();
                                for (Update update : updates) {
                                    if (!(update.isCancelled() || update.isComplete())) {
                                        done = false;
                                        break;
                                    }
                                }
                            }
                            if (done) {
                                try {
                                    Thread.sleep(5000);
                                } catch (Throwable e) {
                                }
                                synchronized (UpdateCheckInstanceImpl.class) {
                                    active_checker = null;
                                }
                                break;
                            }
                        }
                    }
                }
            }.start();
        } else {
            run_now = false;
            // System.out.println( "UCI: waiting " + getName());
            new AEThread2("UCI:waiter") {

                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                        } catch (Throwable e) {
                        }
                        boolean retry = false;
                        synchronized (UpdateCheckInstanceImpl.class) {
                            if (active_checker == null) {
                                retry = true;
                            }
                        }
                        if (retry) {
                            UpdateCheckInstanceImpl.this.start();
                            break;
                        }
                    }
                }
            }.start();
        }
    }
    if (run_now) {
        startSupport();
    }
}
Also used : AEThread2(com.biglybt.core.util.AEThread2)

Example 10 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class UpdateCheckInstanceImpl method startSupport.

private void startSupport() {
    for (int i = 0; i < components.length; i++) {
        final UpdateCheckerImpl checker = checkers[i];
        new AEThread2("UpdatableComponent Checker:" + i, true) {

            @Override
            public void run() {
                try {
                    checker.getComponent().checkForUpdate(checker);
                } catch (Throwable e) {
                    checker.reportProgress("Update check failed: " + Debug.getNestedExceptionMessage(e));
                    e.printStackTrace();
                    checker.failed();
                }
            }
        }.start();
    }
    new AEThread2("UpdatableComponent Completion Waiter", true) {

        @Override
        public void run() {
            for (int i = 0; i < components.length; i++) {
                sem.reserve();
            }
            try {
                boolean mandatory_failed = false;
                for (int i = 0; i < checkers.length; i++) {
                    if (components[i].isMandatory() && checkers[i].getFailed()) {
                        mandatory_failed = true;
                        break;
                    }
                }
                List<UpdateImpl> target_updates = new ArrayList<>();
                if (mandatory_failed) {
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "Dropping all updates as a mandatory update check failed"));
                } else {
                    // If there are any manadatory updates then we just go ahead with them and drop the rest
                    boolean mandatory_only = false;
                    for (int i = 0; i < updates.size(); i++) {
                        UpdateImpl update = (UpdateImpl) updates.get(i);
                        if (update.isMandatory()) {
                            mandatory_only = true;
                            break;
                        }
                    }
                    for (int i = 0; i < updates.size(); i++) {
                        UpdateImpl update = (UpdateImpl) updates.get(i);
                        if (update.isMandatory() || !mandatory_only) {
                            target_updates.add(update);
                        } else {
                            if (Logger.isEnabled())
                                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "Dropping update '" + update.getName() + "' as non-mandatory and " + "mandatory updates found"));
                        }
                    }
                }
                // maintain order here as we apply updates in the order we
                // were requested to
                Collections.sort(target_updates, new Comparator<UpdateImpl>() {

                    @Override
                    public int compare(UpdateImpl o1, UpdateImpl o2) {
                        int i1 = getIndex(o1);
                        int i2 = getIndex(o2);
                        return (i1 - i2);
                    }

                    private int getIndex(UpdateImpl update) {
                        UpdatableComponentImpl component = update.getComponent();
                        for (int i = 0; i < components.length; i++) {
                            if (components[i] == component) {
                                return (i);
                            }
                        }
                        Debug.out("Missing component!");
                        return (0);
                    }
                });
                updates = target_updates;
            } finally {
                try {
                    this_mon.enter();
                    if (cancelled) {
                        return;
                    }
                    completed = true;
                } finally {
                    this_mon.exit();
                }
            }
            for (int i = 0; i < listeners.size(); i++) {
                try {
                    ((UpdateCheckInstanceListener) listeners.get(i)).complete(UpdateCheckInstanceImpl.this);
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
        }
    }.start();
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) AEThread2(com.biglybt.core.util.AEThread2)

Aggregations

AEThread2 (com.biglybt.core.util.AEThread2)20 File (java.io.File)6 PluginInterface (com.biglybt.pif.PluginInterface)5 Map (java.util.Map)5 GridData (org.eclipse.swt.layout.GridData)4 HashMap (java.util.HashMap)3 GridLayout (org.eclipse.swt.layout.GridLayout)3 DiskManagerFileInfoURL (com.biglybt.core.download.DiskManagerFileInfoURL)2 MessageText (com.biglybt.core.internat.MessageText)2 LogEvent (com.biglybt.core.logging.LogEvent)2 AESemaphore (com.biglybt.core.util.AESemaphore)2 PluginListener (com.biglybt.pif.PluginListener)2 IPCInterface (com.biglybt.pif.ipc.IPCInterface)2 Update (com.biglybt.pif.update.Update)2 ResourceDownloader (com.biglybt.pif.utils.resourcedownloader.ResourceDownloader)2 ResourceDownloaderAdapter (com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderAdapter)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 Button (org.eclipse.swt.widgets.Button)2