-
-
Save reusee/7372569 to your computer and use it in GitHub Desktop.
extract subtitle stream from mkv file, using libav
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
#cgo LDFLAGS: -lavformat -lavutil -lavcodec | |
#include <libavformat/avformat.h> | |
#include <libavutil/avutil.h> | |
*/ | |
import "C" | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"unsafe" | |
) | |
func main() { | |
C.av_register_all() | |
var ctx *C.AVFormatContext | |
if C.avformat_open_input(&ctx, C.CString(os.Args[1]), nil, nil) != C.int(0) { | |
log.Fatalf("cannot open file\n") | |
} | |
streams := (*[1 << 30]*C.AVStream)(unsafe.Pointer(ctx.streams)) | |
for i := C.uint(0); i < ctx.nb_streams; i++ { | |
stream := streams[i] | |
if stream.codec.codec_type != C.AVMEDIA_TYPE_SUBTITLE { | |
continue | |
} | |
codec := C.avcodec_find_decoder(stream.codec.codec_id) | |
if C.avcodec_open2(stream.codec, codec, nil) != C.int(0) { | |
log.Fatalf("error opening codec\n") | |
} | |
} | |
var packet C.AVPacket | |
C.av_init_packet(&packet) | |
var gotSub, result C.int | |
var subtitle C.AVSubtitle | |
var stream *C.AVStream | |
var start, end C.int64_t | |
var rects *[1 << 31]*C.AVSubtitleRect | |
var rect *C.AVSubtitleRect | |
var i C.uint | |
for C.av_read_frame(ctx, &packet) >= C.int(0) { | |
stream = streams[packet.stream_index] | |
if stream.codec.codec_type != C.AVMEDIA_TYPE_SUBTITLE { | |
continue | |
} | |
result = C.avcodec_decode_subtitle2(stream.codec, &subtitle, &gotSub, &packet) | |
if result >= C.int(0) { | |
start = packet.pts*C.int64_t(1000*stream.time_base.num/stream.time_base.den) + C.int64_t(subtitle.start_display_time) | |
end = packet.pts*C.int64_t(1000*stream.time_base.num/stream.time_base.den) + C.int64_t(subtitle.end_display_time) | |
fmt.Printf("%d %d\n", start, end) | |
rects = (*[1 << 31]*C.AVSubtitleRect)(unsafe.Pointer(subtitle.rects)) | |
for i = C.uint(0); i < subtitle.num_rects; i++ { | |
rect = rects[i] | |
if rect._type == C.SUBTITLE_ASS { | |
fmt.Printf("=>%s<=\n", C.GoString(rect.ass)) | |
} else if rect._type == C.SUBTITLE_TEXT { | |
fmt.Printf("=>%s<=\n", C.GoString(rect.text)) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment