hdmv pgs что это

Субтитры PGS что такое?

Держи
Субтитры могут быть представлены в виде отдельного файла с расширением соответствующем формату субтитров, либо включены в медиаконтейнер, например в MKV. В характеристиках каждого медиаплеера обязательно указываются форматы поддерживаемых субтитров. Существует множество форматов цифровых внешних субтитров, отображение которых возможно при просмотре фильмов на медиаплеерах. Именно о них мы расскажем ниже.

SubRipper(SRT) – это рабочий файл субтитров программы SubRip, которая является одной из самых популярных для извлечения субтитров из DVD. Данный формат является одним из самых распространенных и удобных для редактирования, отличается простотой и наглядностью, синхронизируется с видео на основе времени с точностью до микросекунд. Изначально не поддерживал элементов оформления текста, но в дальнейшем был расширен поддержкой цветов и начертаний символов (курсив, жирность текста).

SubViewer и Submagic(SUB) – популярный в прошлом формат, предназначенный для проигрывания в программе Submagic. Ввиду распространения более новых форматов субтитров утрачивает свою актуальность. В файле субтитров могут быть указаны настройки шрифта.

Advanced SubStation Alpha(ASS) – формат с неблагозвучным для знающих английский расширением является дальнейшим развитием SubStation Alpha. Расширенный формат содержит такие возможности, как использование векторной графики и подсветки текста в режиме караоке.

SUP – двоичный формат графических субтитров, используемый в VOB-файлах DVD диска, а так же в Blue Ray дисках.

Presentation Graphic Streams(PGS) – сравнительно новый формат субтитров использующийся в Blue Ray дисках.

Timed Text(TT) – один из наиболее перспективных форматов субтитров, основанный на XML.

Источник

Автоматизация выгрузки субтитров из *.mkv файлов

Пару месяцев назад у меня появился телевизор со SmartTV от Samsung. Девайс быстро подружился с медиацентром (роль которого исполняет Plex Media Server) с помощью нативного приложения, однако почти сразу же обнаружился весьма неприятный недостаток — отсутствие поддержки вшитых субтитров в *.mkv. Перспектива ручками извлекать субтитры из каждого файла меня отнюдь не радовала, и, поскольку торрент-клиент крутится на той же машине, что и медиасервер, было принято решение автоматизировать процесс обработки скачанных фильмов.

Под катом — рассказ о том, как при помощи 30 строчек кода на js пары шелл-скриптов и плагина для Deluge привести *mkv-файлы в удобоваримый для телевизора вид.

Исходные данные

Итак, у нас есть: headless-машина с Ubuntu Server 12.04LTS, Deluge 1.3.5 и Plex Media Server 0.9.7.28 с веб-интерфейсом. Для начала составим мини-ТЗ.

Хук для deluge

В базовой установке Deluge присутствует плагин Execute, позволяющий выполнить произвольный скрипт при добавлении торрента и/или завершении его загрузки (документацию и примеры можно посмотреть здесь). Нас же интересует лишь точный формат передаваемых аргументов, описания которого в манах нет, но пример которого можно легко получить с помощью тестового скрипта:

Сохраним скрипт в какой-нибудь общедоступной директории (я использовал для этого кастомную директорию /specshare) под именем testhook.sh и дадим нужные права на исполнение с помощью

Последний шаг необходим, иначе скрипт попросту не будет вызываться, при этом корректно отображаясь в настройках. Теперь ставим на закачку небольшой торрент и получаем в файле sample.txt что-то вроде:

1759d534dbe371565632ec0cccbb1579d344c5ca
Totally.Legal.Open.Source.Software.iso
/store/distribs

Первый параметр — универсальный идентификатор торрента, позволяющий запросить по нему у демона дополнительную информацию. Второй — имя торрента; как правило, это либо имя файла, либо имя директории (если файлов в раздаче несколько). Третий — имя родительской папки для торрента.

Теперь, когда мы знаем, как выглядят входные параметры, создадим два файла в той же директории, где лежал testhook.sh: extractor.sh и deluge-movie-callback.sh. Первый скрипт будет отвечать за непосредственное извлечение субтитров, и к нему мы вернемся чуть позже, а во второй файл введем следующее:

Извлечение субтитров

Для извлечения дорожек с субтитрами воспользуемся пакетом mkvtoolnix. Установка проста:

Нас интересует две утилиты: mkvmerge и mkvextract. Первая позволяет получить список потоков в контейнере:

Формальной, для этой цели предназначена утилита mkvinfo из того же пакета, однако вывод mkvmerge лаконичней и гораздо лучше поддается парсингу. На выходе мы получим примерно такой список:

Track ID 1: video (V_MPEG4/ISO/AVC) [language:eng track_name:The\sMatrix\s1999\s1080p\sBluRay\sDD5.1\sx264-CtrlHD display_dimensions:1280×532 default_track:0 forced_track:0 packetizer:mpeg4_p10_video default_duration:41708332]
Track ID 2: audio (A_AC3) [language:rus track_name:DUB-Blu-ray default_track:1 forced_track:0 default_duration:32000000 audio_sampling_frequency:48000 audio_channels:6]

Track ID 9: audio (A_DTS) [language:eng track_name:Original default_track:0 forced_track:0 default_duration:10666666 audio_sampling_frequency:48000 audio_channels:6]
Track ID 10: subtitles (S_TEXT/UTF8) [language:rus track_name:Sub default_track:0 forced_track:0]
Track ID 11: subtitles (S_TEXT/UTF8) [language:rus track_name:Sub-(по\s\2правильному\2\sпереводу\sГоблина) default_track:0 forced_track:0]
Track ID 12: subtitles (S_TEXT/UTF8) [language:eng track_name:Sub default_track:0 forced_track:0]
Track ID 13: subtitles (S_TEXT/UTF8) [language:eng track_name:Sub-SDH default_track:0 forced_track:0]

Нас интересуют потоки с типом subtitles и кодеком S_TEXT/UTF8, для которых нам нужен TrackID и код языка. Помимо S_TEXT/UTF8 мне встречались субтитры с кодировкой S_HDMV/PGS, но это птица редкая, требует она конвертации в srt, и поэтому субтитры такого типа мы рассматривать не будем. Заинтересовавшимся предлагают обратить внимание на утилиту BDSup2Sub.

Для непосредственного извлечения потока используем:

Первые два параметра (TrackID и имя файла-контейнера) довольно очевидны, а вот с третьим — именем для файла с субтитрами — все немного сложнее. Здесь необходимо ненадолго прерваться и ознакомиться с правилами именования внешних субтитров в Plex.

Согласно приведенной спецификации, имя субтитров должно иметь формат
Алгоритм прост: мы запрашиваем список потоков, каждый из них разбираем регуляркой и, при выполнении условий для типа/кодека/языка, извлекаем файл. К сожалению, мне не удалось заставить работать квантификаторы для capturing groups в POSIX-версии регекспов, поэтому ситуация, когда язык для субтитров отсутствует, обрабатывается отдельной версией регулярного выражения. Буду рад советам на тему того, как это поправить.

Обновлением медиатеки

Консольный метод
Метод с GET-запросом

Веб-панель PMS, помимо предоставления UI для управления медиатекой, позволяет использовать GET-запросы к определенным URL для запуска сканирования. Для этого URL должен иметь следующий вид:

Теперь, когда мы знаем адрес, откроем снова deluge-movie-callback.sh и добавим в конец что-то вроде

У нас готовы оба скрипта, осталось дать им права на запуск и добавить deluge-movie-callback.sh в настройки Execute. Этот процесс уже рассматривался, так что я не буду заострять на нем внимание.

Читайте также:  halogen плита что такое

Источник

Subtitles

Because Matroska is a general container format, we try to avoid specifying the formats to store in it. This type of work is really outside of the scope of a container-only format. However, because the use of subtitles in A/V containers has been so limited (with the exception of DVD) we are taking the time to specify how to store some of the more common subtitle formats in Matroska. This is being done to help facilitate their growth. Otherwise, incompatibilities could prevent the standardization and use of subtitle storage.

This page is not meant to be a complete listing of all subtitle formats that will be used in Matroska, it is only meant to be a guide for the more common, current formats. It is possible that we will add future formats to this page as they are created, but it is not likely as any other new subtitle format designer would likely have their own specifications. Any specification listed here SHOULD be strictly adhered to or it SHOULD NOT use the corresponding Codec ID.

Here is a list of pointers for storing subtitles in Matroska:

Images Subtitles

The first image format that is a goal to import into Matroska is the VobSub subtitle format. This subtitle type is generated by exporting the subtitles from a DVD.

If there is more than one subtitle stream in the VobSub set, each stream will need to be separated into separate tracks for storage in Matroska. E.g. the VobSub file contains streams for both English and German subtitles. Then the resulting Matroska file SHOULD contain two tracks. That way the language information can be dropped and mapped to Matroska’s language tags.

First, lines beginning with “#” are removed. These are comments to make text file editing easier, and as this is not a text file, they aren’t needed.

Next remove the “langidx” and “id” lines. These are used to differentiate the subtitle streams and define the language. As the streams will be stored separately anyway, there is no need to differentiate them here. Also, the language setting will be stored in the Matroska tags, so there is no need to store it here.

Finally, the “timestamp” will be used to set the Block’s timestamp. Once it is set there, there is no need for it to be stored here. Also, as it may interfere if the file is edited, it SHOULD NOT be stored here.

Once all of these items are removed, the data to store in the CodecPrivate SHOULD look like this:

There SHOULD also be two Blocks containing one image each with the timestamps “00:00:01:101” and “00:00:08:708”.

SRT Subtitles

SRT is perhaps the most basic of all subtitle formats.

It consists of four parts, all in text:

1. A number indicating which subtitle it is in the sequence. 2. The time that the subtitle appears on the screen, and then disappears. 3. The subtitle itself. 4. A blank line indicating the start of a new subtitle.

When placing SRT in Matroska, part 3 is converted to UTF-8 (S_TEXT/UTF8) and placed in the data portion of the Block. Part 2 is used to set the timestamp of the Block, and BlockDuration element. Nothing else is used.

Here is an example SRT file:

In this example, the text “Senator, we’re making our final approach into Coruscant.” would be converted into UTF-8 and placed in the Block. The timestamp of the block would be set to “00:02:17,440”. And the BlockDuration element would be set to “00:00:02,935”.

The same is repeated for the next subtitle.

Because there are no general settings for SRT, the CodecPrivate is left blank.

SSA/ASS Subtitles

SSA stands for Sub Station Alpha. It’s the file format used by the popular subtitle editor, SubStation Alpha. This format is widely used by fansubbers.

It allows you to do some advanced display features, like positioning, karaoke, style managements…

For detailed information on SSA/ASS, see the SSA specs. It includes an SSA specs description and the advanced features added by ASS format (standing for Advanced SSA). Because SSA and ASS are so similar, they are treated the same here.

Like SRT, this format is text based with a particular syntax.

The first, “[Script Info]” contains some information about the subtitle file, such as it’s title, who created it, type of script and a very important one: “PlayResY”. Be careful of this value, everything in your script (font size, positioning) is scaled by it. Sub Station Alpha uses your desktops Y resolution to write this value, so if a friend with a large monitor and a high screen resolution gives you an edited script, you can mess everything up by saving the script in SSA with your low-cost monitor.

The second, “[V4 Styles]”, is a list of style definitions. A style describe how will look a text on the screen. It defines font, font size, primary/…/outile colour, position, alignment, etc.

The third, “[Events]”, is the list of text you want to display at the right timing. You can specify some attribute here. Like the style to use for this event (MUSTbe defined in the list), the position of the text (Left, Right, Vertical Margin), an effect. Name is mostly used by translator to know who said this sentence. Timing is in h:mm:ss.cc (centisec).

Читайте также:  что делать если все сервера в black russia заполнены

“[Pictures]” or “[Fonts]” part can be found in some SSA file, they contains UUE-encoded pictures/font but those features are only used by Sub Station Alpha – i.e. no filter (Vobsub/Avery Lee Subtiler filter) use them.

Now, how are they stored in Matroska?

Here is an example of an SSA file.

Here is what would be placed into the CodecPrivate element.

And here are the two blocks that would be generated.

Block’s timestamp: 00:02:40.650 BlockDuration: 00:00:01.140

Block’s timestamp: 00:02:42.420 BlockDuration: 00:00:01.730

WebVTT

The “Web Video Text Tracks Format” (short: WebVTT) is developed by the World Wide Web Consortium (W3C). Its specifications are freely available.

The guiding principles for the storage of WebVTT in Matroska are:

Storage of WebVTT in Matroska

CodecID: codec identification

CodecPrivate: storage of global WebVTT blocks

This element contains all global blocks before the first subtitle entry. This starts at the “ WEBVTT ” file identification marker but excludes the optional byte order mark.

Storage of non-global WebVTT blocks

Non-global WebVTT blocks (e.g., “NOTE”) before a WebVTT Cue Text are stored in Matroska’s BlockAddition element together with the Matroska Block containing the WebVTT Cue Text these blocks precede (see below for the actual format).

Storage of Cues in Matroska blocks

Each WebVTT Cue Text is stored directly in the Matroska Block.

A muxer MUST change all WebVTT Cue Timestamps present within the Cue Text to be relative to the Matroska Block’s timestamp.

The Cue’s start timestamp is used as the Matroska Block’s timestamp.

The difference between the Cue’s end timestamp and its start timestamp is used as the Matroska Block’s duration.

BlockAdditions: storing non-global WebVTT blocks, Cue Settings Lists and Cue identifiers

Each Matroska Block may be accompanied by one BlockAdditions element. Its format is as follows:

If there is no Matroska BlockAddition element stored together with the Matroska Block, then all three components (Cue Settings List, Cue Identifier, Cue Comments) MUST be assumed to be absent.

Examples of transformation

Here’s an example how a WebVTT is transformed.

Example WebVTT file

Let’s take the following example file:

Example of CodecPrivate

The resulting CodecPrivate element will look like this:

Storage of Cue 1

Example Cue 1: timestamp 00:00:00.000, duration 00:00:10.000, Block’s content:

BlockAddition’s content starts with one empty line as there’s no Cue Settings List:

Storage of Cue 2

Example Cue 2: timestamp 00:00:25.000, duration 00:00:10.000, Block’s content:

BlockAddition’s content starts with two empty lines as there’s neither a Cue Settings List nor a Cue Identifier:

Storage of Cue 3

Example Cue 3: timestamp 00:01:03.000, duration 00:00:03.500, Block’s content:

BlockAddition’s content ends with an empty line as there’s no Cue Identifier and there were no WebVTT Comment blocks:

Storage of Cue 4

Example Cue 4: timestamp 00:03:10.000, duration 00:00:10.000, Block’s content:

Example entry 4: Entries can even include timestamps. For example: This becomes visible five seconds after the first part.

This Block does not need a BlockAddition as the Cue did not contain an Identifier, nor a Settings List, and it wasn’t preceded by Comment blocks.

Storage of WebVTT in Matroska vs. WebM

Note: the storage of WebVTT in Matroska is not the same as the design document for storage of WebVTT in WebM. There are several reasons for this including but not limited to: the WebM document is old (from February 2012) and was based on an earlier draft of WebVTT and ignores several parts that were added to WebVTT later; WebM does still not support subtitles at all; the proposal suggests splitting the information across multiple tracks making demuxer’s and remuxer’s life very difficult.

HDMV presentation graphics subtitles

The specifications for the HDMV presentation graphics subtitle format (short: HDMV PGS) can be found in the document “Blu-ray Disc Read-Only Format; Part 3 — Audio Visual Basic Specifications” in section 9.14 “HDMV graphics streams”.

Storage of HDMV presentation graphics subtitles

Storage of HDMV PGS Segments in Matroska Blocks

Each HDMV PGS Segment (short: Segment) will be stored in a Matroska Block. A Segment is the data structure described in section 9.14.2.1 “Segment coding structure and parameters” of the Blu-ray specifications.

Each Segment contains a presentation timestamp. This timestamp will be used as the timestamp for the Matroska Block.

A Segment is normally shown until a subsequent Segment is encountered. Therefore the Matroska Block MAY have no Duration. In that case, a player MUST display a Segment within a Matroska Block until the next Segment is encountered.

A muxer MAY use a Duration, e.g., by calculating the distance between two subsequent Segments. If a Matroska Block has a Duration, a player MUST display that Segment only for the duration of the Block’s Duration.

HDMV text subtitles

The specifications for the HDMV text subtitle format (short: HDMV TextST) can be found in the document “Blu-ray Disc Read-Only Format; Part 3 — Audio Visual Basic Specifications” in section 9.15 “HDMV text subtitle streams”.

Storage of HDMV text subtitles

A CodecPrivate Element is required. It MUST contain the stream’s Dialog Style Segment as described in section 9.15.4.2 “Dialog Style Segment” of the Blu-ray specifications.

Storage of HDMV TextST Dialog Presentation Segments in Matroska Blocks

Each HDMV Dialog Presentation Segment (short: Segment) will be stored in a Matroska Block. A Segment is the data structure described in section 9.15.4.3 “Dialog presentation segment” of the Blu-ray specifications.

Читайте также:  какой лучше spf для загара

Each Segment contains a start and an end presentation timestamp (short: start PTS & end PTS). The start PTS will be used as the timestamp for the Matroska Block. The Matroska Block MUST have a Duration, and that Duration is the difference between the end PTS and the start PTS.

A player MUST use the Matroska Block’s timestamp and Duration instead of the Segment’s start and end PTS for determining when and how long to show the Segment.

Character set

When TextST subtitles are stored inside Matroska, the only allowed character set is UTF-8.

Each HDMV text subtitle stream in a Blu-ray can use one of a handful of character sets. This information is not stored in the MPEG2 Transport Stream itself but in the accompanying Clip Information file.

Therefore a muxer MUST parse the accompanying Clip Information file. If the information indicates a character set other than UTF-8, it MUST re-encode all text Dialog Presentation Segments from the indicated character set to UTF-8 prior to storing them in Matroska.

Digital Video Broadcasting (DVB) subtitles

Storage of DVB subtitles

CodecID

CodecPrivate

The CodecPrivate element is five bytes long and has the following structure:

The semantics of these bytes are the same as the ones described in section 6.2.41 “Subtitling descriptor” of ETSI EN 300 468.

Storage of DVB subtitles in Matroska Blocks

Each Matroska Block consists of one or more DVB Subtitle Segments as described in segment 7.2 “Syntax and semantics of the subtitling segment” of ETSI EN 300 743.

Each Matroska Block SHOULD have a Duration indicating how long the DVB Subtitle Segments in that Block SHOULD be displayed.

Источник

Неизвестное расширение файла может быть источником различных проблем. Однако выявление причин проблем с файлами PGS и их устранение не являются сложным процессом. Эта статья опишет 5 простых шагов, которые позволят вам решить проблемы с файлами PGS.

PGS расширение файла

Как открыть файл PGS?

Шаг 1. Найдите и скачайте и установите соответствующее программное обеспечение

Обычно для открытия файлов. PGS достаточно выполнить следующие простые шаги: найти, загрузить и установить соответствующее программное обеспечение. Затем, дважды щелкнув значок файла, откройте файл. Система должна автоматически связать PGS файл с соответствующим программным обеспечением. Ниже приведен список программ, необходимых для открытия файлов с расширением PGS:

Программы, поддерживающие PGS файлы

Шаг 2. Убедитесь, что файл PGS не заражен вредоносным ПО

Если данный файл с расширением PGS не заражен, возможно, антивирусная программа блокирует доступ к файлу. Пользователь должен принять необходимые меры предосторожности и выполнить действия, предложенные системой. После восстановления или удаления зараженного файла рекомендуется проверить всю систему на наличие вирусов. Вам нужно будет приобрести новую, чистую версию файла PGS.

Подсказка!

Имейте в виду, что вы всегда можете обратиться за помощью к ИТ-специалисту. Некоторые проблемы с файлами PGS могут быть трудно решить для менее опытных пользователей. Также вы можете обратиться за помощью к одному из разработчиков программного обеспечения, которое поддерживает файлы с расширением PGS. Для этого перейдите на подстраницу программного обеспечения и найдите адрес веб-сайта разработчика программного обеспечения.

Шаг 3. Убедитесь, что файлы PGS завершены, то есть были ли они загружены правильно

Если файл PGS не был загружен должным образом, программное обеспечение не сможет открыть такой файл. Проверьте размер файла в том месте, откуда вы скачали нужный файл. Если размер исходного файла отличается от размера загруженного файла PGS, вам придется загрузить файл снова.

Шаг 4. Убедитесь, что файлы PGS связаны с соответствующим программным обеспечением

Шаг 5. Убедитесь, что носитель, на котором хранятся файлы PGS, не поврежден или не поврежден

Возможно, что носитель, на котором находится файл, поврежден или поврежден. Попробуйте сканировать носитель на наличие ошибок.

Источник

FFmpeg: ошибка при копировании потоков субтитров с помощью iFFmpeg

Прежде всего: я новичок в этом сайте и не очень опытен с FFmpeg, поэтому я использую графический интерфейс iFFmpeg для Mac OS X. Кроме того, мой родной язык не английский.

Итак, вот моя проблема: я получил входной файл MKV с несколькими потоками аудио и субтитров, и я хочу сжать его в M4V-контейнер с двумя аудио-потоками и одним потоком субтитров. Кодирование видеопотока и двух аудиопотоков работает нормально, но когда я пытаюсь добавить поток субтитров, он отправляет мне сообщение об ошибке: «Не удалось открыть поток кодировщика».

Я предполагаю, что iFFmpeg что-то не так с параметрами субтитров. Я пытался исправить это, но пока не мог понять.

Это мой входной файл:

Поток # 0: 0(англ): Видео: h264 (High), yuv420p, 1920×1080 [SAR 1: 1 DAR 16: 9], 24 кадра в секунду, 24 тбр, 1 т тбн, 48 тбк

Поток # 0: 1 (deu): аудио: dts (DTS-HD MA), 48000 Гц, 5.1 (сторона), fltp, 1536 кбит / с (по умолчанию)

Поток # 0: 2 (deu): аудио: dts (DTS), 48000 Гц, 5.1 (сторона), fltp, 1536 кбит / с

Поток № 0: 3 (англ.): Аудио: dts (DTS-HD MA), 48000 Гц, 5.1 (сбоку), fltp, 1536 кбит / с

Поток # 0: 4 (англ): аудио: dts (DTS), 48000 Гц, 5.1 (сторона), fltp, 1536 кбит / с

Поток № 0: 5 (deu): подзаголовок: hdmv_pgs_subtitle

Поток № 0: 6 (deu): подзаголовок: hdmv_pgs_subtitle

Поток № 0: 7 (deu): подзаголовок: hdmv_pgs_subtitle

Поток № 0: 8 (англ): Подзаголовок: hdmv_pgs_subtitle

Поток № 0: 9 (англ): подзаголовок: hdmv_pgs_subtitle

Поток № 0: 10: вложение: mjpeg

И вот что iFFmpeg генерирует меня как команду (я знаю, довольно долго):

Я был бы очень рад, если бы кто-нибудь мог мне помочь, потому что я пытался так долго, и это просто расстраивает, что это не работает.

Источник

Сказочный портал