- Стрим видео с Android устройства по UDP в JAVA приложение
- Инсталляция пакета VLCJ
- Надо разобраться
- Казалось бы победа?
- How do you Fullscreen RTSP Stream in Android LibVLC?
- 2 Answers 2
- VLC for Android: Play YouTube, Dailymotion, and Online Video Streams
- Which video site works?
- 17 thoughts to “VLC for Android: Play YouTube, Dailymotion, and Online Video Streams”
Стрим видео с Android устройства по UDP в JAVA приложение
Итак, выходим на финишную прямую. Стримить видео с андроида на VLC плеер мы уже научились, теперь осталось только интегрировать окошко с видео в JAVA приложение и начать рулить роботелегой.
В этом нам очень сильно поможет проект с открытым исходным кодом VLCJ CAPRICA.
The vlcj project provides a Java framework to allow an instance of a native VLC media player to be embedded in a Java application.
Идея у ребят простая, но гениальная (реально перцовая). Вместо мучений с библиотеками FFmpeg и прочим, надо сразу вызывать специалиста ядро нормального, функционального и профессионального медиаплеера VLC. И вызвать его прямо из JAVA приложения.
Кому интересно, просим под кат.
Поскольку, в этом вояже хватает подводных камней, то начнём, как водится, с очень простого и лишь затем перейдём к тривиальному.
Инсталляция пакета VLCJ
Первым делом проверьте установленную у вас версию медиапроигрывателя VLC. Свежая версия нам не нужна, там выпилено то, что требуется для udp стрима. Об этом уже говорилось в предыдущем посту. Поэтому качаем версию 2.2.6 Umbrella и заодно тщательно проверяем свой JAVA пакет. Они должны совпадать по разрядности. Если плеер использует 64-разрядную архитектуру, то и JDK обязан быть таким же. А то не взлетит.
После этого уже можно скачать сам пакет библиотек VLCJ
Обратите внимание, что нам нужен пакет vlcj-3.12.1 distribution (zip). Именно он работает с плеерами версий VLC 2.2.x. Разархивировать его можно куда угодно, главное, что не в папку самого VLC, ибо там по именам совпадают два файла. И если вы их перезапишите, кончится всё это полным провалом.
Далее, создаем проект в IDE IntelliJ IDEA (если у вас другое IDE, то ничем помочь не могу) и прописываем необходимые зависимости для интеграции библиотек VLCJ.
Делаем именно так для файлов:
Затем создаем единственный класс и пишем в нём следующую малюсенькую программку.
Да, пока мы пытаемся проигрывать просто файл (как видно из кода). С udp лучше не начинать — не заработает. А файл проигрывается вполне, если вы, конечно, не забыли его с соответствующим именем разместить заранее там, где надо. Думаю, что даже для самого начинающего джависта не составит труда разобраться в вышеприведенном коде.
и создание самого инстанса медиаплеера
А потом мы просто его добавляем в нужную графическую панель:
И всё, файл будет проигрываться именно в этом окошке.
А теперь попробуйте заменить
как мы спокойно делали в прошлом посте для стриминга видео через udp соединение.
Здесь такой номер не пройдёт. Окошко, конечно откроется, но покажет фигу, в смысле темный экран. Хотя никаких логов с ошибкой не будет. Просто не будет ничего.
Надо разобраться
Может быть не хватает кодека H264, который мы выбрали в настройках? Стоп, а как тогда только что проигрывался файл ttt.mp4? Он же не может проигрываться при такой настройке, он же — mp4.
Немедленно приходит понимание того, что библиотека VLCJ запускает только само ядро плеера. А какие там были предварительные настройки она не знает и знать не хочет. То есть, нам надо каким-то образом при запуске JAVA приложения, как-то передать VLC плееру, что мы хотим явно использовать кодек H264 или, допустим, хотим повернуть изображение или что-то ещё.
Оказывается, сделать это можно, используя класс MediaPlayerFactory. Только мы его запускали без аргументов, а можно даже с ними. На stackoverflow.com я тут же нашел простой пример, связанный с поворачиванием изображения:
То есть, чего-то там передаем строчным массивом в медиафабрику и оно там сохраняется для используемого медиаресурса.
Я попробовал этот способ для проигрывания файла и как водится, ничего не заработало. Оказывается, забыли две черточки добавить и разнесли по всему интернету. Пришлось догадываться, используя похожий метод transform.
Короче говоря, должно быть:
Теперь наш эталонный файл перекривило как надо!
Дальше будет уже совсем просто:
Для определения кодека, согласно командной строке VLC мы добавляем в строковый массив строку:
Снова пробуем udp канал
И в этот раз всё работает, обозначая победу человеческого разума. Теперь это окошко с видео или несколько таких окошек вы сможете беспрепятственно портировать в графический интерфейс вашего JAVA приложения.
Казалось бы победа?
Не совсем. Легкое недоумение у меня вызвали временные задержки или по научному, лаги. Сначала они более менее приёмлимые, но если у вас хватит терпения просмотреть видео до конца, то вы увидите, что лаг к концу первой минуты трансляции достигает аж пяти секунд. У меня терпения хватило на 10 минут съемки, но, как ни странно, задержка больше не увеличивалась, а так и осталась в тех же пределах.
Конечно, для просмотра видео с камеры такое сгодится, но для управления роботележкой едва ли. Даже луноход реагировал быстрее в два раза!
Подозрения сразу пали на процессы кэширования и они (подозрения )оказались верными.
Самым наглым оказался:
Он как раз и отжирает по умолчанию практически всё, если ему вовремя не дать по рукам.
Может устроить лаг и:
Поэтому во избежание многосекундных задержек рекомендуется добавить во всё тот же строковый массив через запятую следующие строчки:
Параметры там задаются в миллисекундах и поэтому каждый желающий может подобрать их под себя.
Ещё можно использовать ключ:
Тогда медиаплеер будет стараться оптимизировать джитер — подергивание экрана. Но там, чем больше установлено время, тем лучше оптимизируется и это понятно почему. Так что здесь остается лишь искать консенсус и видеть иногда в логах такое безобразие:
Вот хотел он, понимаешь, джиттер исправить, а ты временной промежуток слишком маленький поставил. Теперь сам виноват.
Теперь вроде бы все как надо. Задержку удалось сократить меньше, чем до одной секунды (правда, чуть-чуть меньше).
В итоге, получился совсем крохотный рабочий код
Теперь можно интегрировать видео трансляцию в мою программулину по управлению роботележкой, где раньше я передавал видео по кускам. И надо сказать код весьма упростился, а качество на порядок улучшилось. Плюс ко всему к видео потоку мы можем передать показания
акселерометров
гироскопов
уровня освещения
давления воздуха
показаний компаса
температуры
и даже влажности
При условии, конечно, что все эти сенсоры у вашего смартфона имеются.
И даже включить фару! Автоматически! Если уровень освещения упадёт.
Вряд ли кому особо интересно, но на случай ссылки на гитхаб:
Источник
How do you Fullscreen RTSP Stream in Android LibVLC?
I’m using mrmaffen’s VLC-ANDROID-SDK to develop an RTSP streaming app. https://github.com/mrmaffen/vlc-android-sdk
I’ve had a lot of success getting it working and running quite well, but the problem I’m having that I can’t seem to shake is getting it to display the video feed in fullscreen on the SurfaceView, or even just in the center of the SurfaceView.
This is what I get:
The black window is the total size of the screen, I want that video to fill the screen and hopefully always fill from center, but I can’t figure out how to do it.
Anyone have any experience with anything like this and knows how to fix it?
2 Answers 2
I kind of solved the problem but in a bit of a dodgy way, it’s far from complete but considering the lack of knowledge and information on the topic I thought this might help someone for the time being.
- Find the size of your screen.
- Set up your final IVLCOut to incorporate the screen size.
- Adjust setScale to «fullscreen» the video stream.
To explain each task:
Setup your globals:
Secondly, in the onCreate task find your screen sizes of your device:
2. Then go down to your «CreatePlayer» event and where you set up your video output:
The winning line that made it center in my surface was the «vout.setWindowSize(mWidth,mHeight);»
Then I simply used the setscale option to «fullscreen» the video. That said, it’s a bit of a hack way of doing it, and I would like to try and figure out a way to grab the codec information so to dynamically set the scale of the video and that way automatically fullscreen every size video stream to any size screen but for now this will work for known video stream resolutions, it will automatically adjust to the screen size of your phone.
Either way I found that with a Samsung Galaxy s8, a good scaling factor for a 640x480p RTSP stream was 1.8. Coded like so:
Where you got «mMediaPlayer.setScale(1.8f);»
Hope this helps someone!
your solution seems interesting, however I’m facing the same issues, which I can’t seem to solve (yet) with your approach.
Screenshots of what I got sofar can be seen at: https://photos.app.goo.gl/9nKo22Mkc2SZq4SK9
I also want to (vertically) center an rtsp-video-stream in either landscape/portrait mode on a Samsung-XCover4 (with 720×1280 pixels) and on a device with minimum resolution of 320×480. The minimum Android SDK-version I would love to have it running is API-22 (Android 5.1.1). The libvlc code for which I got the (embedded)VLC-player working, is based on ‘de.mrmaffen:libvlc-android:2.1.12@aar’.
Given the above ‘requirements’, you can see the following behavior in the screenshots. The first two screenshots are on a Samsung-XCover4 (720×1280) where you can see that device-orientation=landscape clips the video and doesn’t scale it, whereas the 3rd and 4th screenshot show that the same video-stream doesn’t follow the SURFACE_BEST_FIT method (see code below for an explanation) on a device with small-resolution. I would love to see an updateVideoSurfaces to handle the change in device-orientation or at least to show the entire video on startup.
The layout for my VLC-video-player (part of a vertical LinearLayout) is as follows:
The example code I got from de.mrmaffen uses an updateVideoSurfaces (see below java-code) which uses a number of SURFACE_XX method which to me seem to cover all scenarios with different device-orientations and resolution.
For some reason I can’t figure out why this doesn’t work and I suspect that the layout I’m using for the player (the FrameLayout/ViewStub’s) may cause the issues.
I was wondering if you can shed some light on directions in order to make sure that the video stream will auto-scale/center on any device orientation/resolution.
Источник
VLC for Android: Play YouTube, Dailymotion, and Online Video Streams
VLC for Android can play YouTube, Dailymotion, Vimeo and other online video streams just like its desktop counterpart. The Android app can open videos using their URL and it will begin to stream immediately. Just copy and paste the link to the video in ☰ > Stream and it will load the video within the VLC app. When an online video is opened using VLC application, features of the Android app can be used on the stream as well.
An online video opened in VLC for Android can have its playback speed increased or decreased, subtitles can be loaded automatically or manually and even be formatted, audio speed can be controlled and synced. There is a whole host of features that come with VLC for Android and it is all available in an ad-free app. So, watch a YouTube video in 1.5x speed, sync the audio for Dailymotion videos or disable the video and hear just the audio of Vimeo streams. But the app does not continue playing the video when the phone is locked.
Here are the detailed steps to play YouTube, Dailymotion, Vimeo and Other Online Video Streams in VLC for Android:
- Copy the direct link to the video from your browser
- Switch to VLC for Android app
- Tap on Menu☰
- Go to Stream
- Long press under Enter network address and hit Paste
The video will open shortly. Feel free to use the on-screen interface controls to navigate the video and switch video resolution. Using the More … option, you can set a timer, control playback speed, skip to time, use the equalizer, cut of the video to play just the audio, delay subtitles, delay audio, use picture-in-picture mode and enable/disable audio digital output for the video.
For copying and pasting the video URL: If it is from a site like Dailymotion or YouTube, open up the full video page first. Example: https://www.dailymotion.com/video/x6emr5p or https://m.youtube.com/watch?v=Z-ap5Fp2T6c . It doesn’t support playlists.
Which video site works?
We have tried it with popular video hosting sites like YouTube, Dailymotion, and Vimeo. They all work. But streams from sites like Twitch, Yahoo View, Break, and Metacafe are not supported. Direct video links to .mp4 files hosted on http:// addresses will certainly work.
If you found additional video sites that work (or doesn’t work) in VLC for Android network streams, then let us know in the comments below.
17 thoughts to “VLC for Android: Play YouTube, Dailymotion, and Online Video Streams”
hi. i have a question. when people copy the youtube url and stream it via the VLC app. do i still get the views for my video in my youtube account.? so if someone streams all my videos as many times in the vlc app. will i get those views, each time that person viewed that video. even if it was 5 times. will i get those 5 views in my youtube account?
How to add a subtitle file to it?
Tap on the screen after opening the stream. The player control menu should display on the bottom. Click on the leftmost button that is for on-screen text (subtitles). On the screen that follows, tap on Subtitles and you can select a subtitle file or download it as per your wish.
One drive and Google drive links not working
hi, will there be an update for vlc android to get youtube links working soon?
thanks
YouTube videos are not streaming even though the title gets displayed after copying and pasting the url. Could you please help me with a resolution for this error.
If you update to the latest version 3.0.11, it should work.
I am facing same issue..do you find any solution, plz guide
I streamed youtoob vids on my laptop using vlc there, no problem. Laptop died, now have Lenovo Android tablet, i have done the exact correct process to stream a youtoob video in vlc app, but it will not stream. It will not play. Nothing whatsoever happens.
I had problems with stream function in VLC Android – app would try to launch audio player and not work after pasting a youtube or dailymotion link in the stream function.
Got it working by uninstalling the VLC and re-installing – now works!
We have downloaded the app seven times we cannot get it to work we have done everything that you’ll tell us who we followed every direction we place the URL address into stream nothing happens
before I setup my VLC Player (android) to play video files from Google Chrome android, instead of playing on it’s browser video elements… but now I forgot how I do that, or may be I need to setup Chrome to play video automatically to VLC?
Источник