Elia
Elia

Reputation: 822

How can I extract PGS/SUP subtitles from mkv container via libav

Trying to write a C code that does the equivalent of the following ffmpeg command:

ffmpeg -i video.mkv -map 0:"$STREAM_INDEX" -c:s copy subtitles.sup

I have managed to read the media container, locate the subtitle streams, and filter the relevant one based on stream metadata. However I only succeeded in getting the bitmap data, without the full PGS header and sections.

Tried dumping packet->data to a file hoping it includes full sections, but the data doesn't start with the expected PGS magic header 0x5047.
Also using avcodec_decode_subtitle2 doesn't seem to be useful as it only gives bitmap data without the full PGS header and sections.

What steps are supposed to happen after finding the relevant subtitle stream that allows extracting it as raw data that exactly matches the output of the ffmpeg command above?

Some sample code:

    while(av_read_frame(container_ctx, packet) == 0) {
      if(packet->stream_index != i) {
        continue;
      }

      // Try 1 - dump packet data to file
      fwrite(packet->data, 1, packet->size, fout);

      // Try 2 - decode subtitles
      int bytes_read = 0, success = 0;
      AVSubtitle sub;

      if ((bytes_read = avcodec_decode_subtitle2(codec_context, &sub, &success, packet)) < 0) {
        fprintf(stderr, "Failed to decode subtitles %s", av_err2str(bytes_read));
        goto end;
      }
      fprintf(stdout, "Success! Status:%d - BytesRead:%d NumRects:%d\n", success, bytes_read, sub.num_rects);

      if (success) {
        // Only managed to extract bitmap data here via sub.rects
      }

      av_packet_unref(packet);
    }

Upvotes: 1

Views: 170

Answers (0)

Related Questions