3 * Copyright (c) 2012 AvxSynth Team.
5 * This file is part of FFmpeg
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavcodec/internal.h"
25 // Enable function pointer definitions for runtime loading.
26 #define AVSC_NO_DECLSPEC
28 // Shut up ffmpeg error messages.
29 // avisynth_c.h contains inline functions that call these functions.
34 // Platform-specific directives for AviSynth vs AvxSynth.
38 #include "compat/avisynth/avisynth_c.h"
39 #define AVISYNTH_LIB "avisynth"
42 #include "compat/avisynth/avxsynth_c.h"
43 #if defined (__APPLE__)
44 #define AVISYNTH_LIB "libavxsynth.dylib"
46 #define AVISYNTH_LIB "libavxsynth.so"
49 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
50 #define GetProcAddress dlsym
51 #define FreeLibrary dlclose
54 // AvxSynth doesn't have these colorspaces, so disable them
56 #define avs_is_yv24(vi) 0
57 #define avs_is_yv16(vi) 0
58 #define avs_is_yv411(vi) 0
59 #define avs_is_y8(vi) 0
64 #define AVSC_DECLARE_FUNC(name) name##_func name
65 AVSC_DECLARE_FUNC(avs_create_script_environment);
66 AVSC_DECLARE_FUNC(avs_delete_script_environment);
67 AVSC_DECLARE_FUNC(avs_get_error);
68 AVSC_DECLARE_FUNC(avs_clip_get_error);
69 AVSC_DECLARE_FUNC(avs_invoke);
70 AVSC_DECLARE_FUNC(avs_release_value);
71 AVSC_DECLARE_FUNC(avs_get_video_info);
72 AVSC_DECLARE_FUNC(avs_take_clip);
73 AVSC_DECLARE_FUNC(avs_release_clip);
74 AVSC_DECLARE_FUNC(avs_bit_blt);
75 AVSC_DECLARE_FUNC(avs_get_audio);
76 AVSC_DECLARE_FUNC(avs_get_frame);
77 AVSC_DECLARE_FUNC(avs_release_video_frame);
78 #undef AVSC_DECLARE_FUNC
81 struct AviSynthContext {
82 AVS_ScriptEnvironment *env;
84 const AVS_VideoInfo *vi;
86 // avisynth_read_packet_video() iterates over this.
96 // Linked list pointers.
97 struct AviSynthContext *next;
99 typedef struct AviSynthContext AviSynthContext;
101 static const int avs_planes_packed[1] = {0};
102 static const int avs_planes_grey[1] = {AVS_PLANAR_Y};
103 static const int avs_planes_yuv[3] = {AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V};
105 // A conflict between C++ global objects, atexit, and dynamic loading requires
106 // us to register our own atexit handler to prevent double freeing.
107 static AviSynthLibrary *avs_library = NULL;
108 static int avs_atexit_called = 0;
110 // Linked list of AviSynthContexts. An atexit handler destroys this list.
111 static AviSynthContext *avs_ctx_list = NULL;
113 static av_cold void avisynth_atexit_handler(void);
115 static av_cold int avisynth_load_library(void) {
116 avs_library = av_mallocz(sizeof(AviSynthLibrary));
118 return AVERROR_UNKNOWN;
120 avs_library->library = LoadLibrary(AVISYNTH_LIB);
121 if (!avs_library->library)
124 #define LOAD_AVS_FUNC(name, continue_on_fail) \
126 avs_library->name = (void*)GetProcAddress(avs_library->library, #name); \
127 if(!continue_on_fail && !avs_library->name) \
130 LOAD_AVS_FUNC(avs_create_script_environment, 0);
131 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
132 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
133 LOAD_AVS_FUNC(avs_clip_get_error, 0);
134 LOAD_AVS_FUNC(avs_invoke, 0);
135 LOAD_AVS_FUNC(avs_release_value, 0);
136 LOAD_AVS_FUNC(avs_get_video_info, 0);
137 LOAD_AVS_FUNC(avs_take_clip, 0);
138 LOAD_AVS_FUNC(avs_release_clip, 0);
139 LOAD_AVS_FUNC(avs_bit_blt, 0);
140 LOAD_AVS_FUNC(avs_get_audio, 0);
141 LOAD_AVS_FUNC(avs_get_frame, 0);
142 LOAD_AVS_FUNC(avs_release_video_frame, 0);
145 atexit(avisynth_atexit_handler);
149 FreeLibrary(avs_library->library);
151 av_freep(&avs_library);
152 return AVERROR_UNKNOWN;
155 // Note that avisynth_context_create and avisynth_context_destroy
156 // do not allocate or free the actual context! That is taken care of
158 static av_cold int avisynth_context_create(AVFormatContext *s) {
159 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
163 if (ret = avisynth_load_library())
167 avs->env = avs_library->avs_create_script_environment(3);
168 if (avs_library->avs_get_error) {
169 const char *error = avs_library->avs_get_error(avs->env);
171 av_log(s, AV_LOG_ERROR, "%s\n", error);
172 return AVERROR_UNKNOWN;
179 avs->next = avs_ctx_list;
186 static av_cold void avisynth_context_destroy(AviSynthContext *avs) {
187 if (avs_atexit_called)
190 if (avs == avs_ctx_list) {
191 avs_ctx_list = avs->next;
193 AviSynthContext *prev = avs_ctx_list;
194 while (prev->next != avs)
196 prev->next = avs->next;
200 avs_library->avs_release_clip(avs->clip);
204 avs_library->avs_delete_script_environment(avs->env);
209 static av_cold void avisynth_atexit_handler(void) {
210 AviSynthContext *avs = avs_ctx_list;
213 AviSynthContext *next = avs->next;
214 avisynth_context_destroy(avs);
217 FreeLibrary(avs_library->library);
218 av_freep(&avs_library);
220 avs_atexit_called = 1;
223 // Create AVStream from audio and video data.
224 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st) {
225 AviSynthContext *avs = s->priv_data;
226 int planar = 0; // 0: packed, 1: YUV, 2: Y8
228 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
229 st->codec->codec_id = CODEC_ID_RAWVIDEO;
230 st->codec->width = avs->vi->width;
231 st->codec->height = avs->vi->height;
233 st->time_base = (AVRational) {avs->vi->fps_denominator, avs->vi->fps_numerator};
234 st->avg_frame_rate = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
236 st->duration = avs->vi->num_frames;
237 st->nb_frames = avs->vi->num_frames;
239 switch (avs->vi->pixel_type) {
242 st->codec->pix_fmt = PIX_FMT_YUV444P;
246 st->codec->pix_fmt = PIX_FMT_YUV422P;
250 st->codec->pix_fmt = PIX_FMT_YUV411P;
254 st->codec->pix_fmt = PIX_FMT_GRAY8;
259 st->codec->pix_fmt = PIX_FMT_BGR24;
262 st->codec->pix_fmt = PIX_FMT_RGB32;
265 st->codec->pix_fmt = PIX_FMT_YUYV422;
268 st->codec->pix_fmt = PIX_FMT_YUV420P;
271 case AVS_CS_I420: // Is this even used anywhere?
272 st->codec->pix_fmt = PIX_FMT_YUV420P;
276 av_log(s, AV_LOG_ERROR, "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
278 return AVERROR_UNKNOWN;
284 avs->planes = avs_planes_grey;
288 avs->planes = avs_planes_yuv;
292 avs->planes = avs_planes_packed;
297 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st) {
298 AviSynthContext *avs = s->priv_data;
300 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
301 st->codec->sample_rate = avs->vi->audio_samples_per_second;
302 st->codec->channels = avs->vi->nchannels;
303 st->time_base = (AVRational) {1, avs->vi->audio_samples_per_second};
305 switch (avs->vi->sample_type) {
306 case AVS_SAMPLE_INT8:
307 st->codec->codec_id = CODEC_ID_PCM_U8;
309 case AVS_SAMPLE_INT16:
310 st->codec->codec_id = CODEC_ID_PCM_S16LE;
312 case AVS_SAMPLE_INT24:
313 st->codec->codec_id = CODEC_ID_PCM_S24LE;
315 case AVS_SAMPLE_INT32:
316 st->codec->codec_id = CODEC_ID_PCM_S32LE;
318 case AVS_SAMPLE_FLOAT:
319 st->codec->codec_id = CODEC_ID_PCM_F32LE;
322 av_log(s, AV_LOG_ERROR, "unknown AviSynth sample type %d\n", avs->vi->sample_type);
324 return AVERROR_UNKNOWN;
329 static int avisynth_create_stream(AVFormatContext *s) {
330 AviSynthContext *avs = s->priv_data;
335 if (avs_has_video(avs->vi)) {
336 st = avformat_new_stream(s, NULL);
338 return AVERROR_UNKNOWN;
340 if (ret = avisynth_create_stream_video(s, st))
343 if (avs_has_audio(avs->vi)) {
344 st = avformat_new_stream(s, NULL);
346 return AVERROR_UNKNOWN;
348 if (ret = avisynth_create_stream_audio(s, st))
354 static int avisynth_open_file(AVFormatContext *s) {
355 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
359 if (ret = avisynth_context_create(s))
362 arg = avs_new_value_string(s->filename);
363 val = avs_library->avs_invoke(avs->env, "Import", arg, 0);
364 if (avs_is_error(val)) {
365 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
366 ret = AVERROR_UNKNOWN;
369 if (!avs_is_clip(val)) {
370 av_log(s, AV_LOG_ERROR, "%s\n", "AviSynth script did not return a clip");
371 ret = AVERROR_UNKNOWN;
375 avs->clip = avs_library->avs_take_clip(val, avs->env);
376 avs->vi = avs_library->avs_get_video_info(avs->clip);
378 // Release the AVS_Value as it will go out of scope.
379 avs_library->avs_release_value(val);
381 if (ret = avisynth_create_stream(s))
387 avisynth_context_destroy(avs);
391 static void avisynth_next_stream(AVFormatContext *s, AVStream **st, AVPacket *pkt, int *discard) {
392 AviSynthContext *avs = s->priv_data;
394 pkt->stream_index = avs->curr_stream++;
395 avs->curr_stream %= s->nb_streams;
397 *st = s->streams[pkt->stream_index];
398 if ((*st)->discard == AVDISCARD_ALL)
406 // Copy AviSynth clip data into an AVPacket.
407 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt, int discard) {
408 AviSynthContext *avs = s->priv_data;
409 AVS_VideoFrame *frame;
410 unsigned char *dst_p;
411 const unsigned char *src_p;
412 int n, i, plane, rowsize, planeheight, pitch, bits;
415 if (avs->curr_frame >= avs->vi->num_frames)
418 // This must happen even if the stream is discarded to prevent desync.
419 n = avs->curr_frame++;
427 // Define the bpp values for the new AviSynth 2.6 colorspaces
428 if (avs_is_yv24(avs->vi)) {
430 } else if (avs_is_yv16(avs->vi)) {
432 } else if (avs_is_yv411(avs->vi)) {
434 } else if (avs_is_y8(avs->vi)) {
437 bits = avs_bits_per_pixel(avs->vi);
440 // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.
441 pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;
443 return AVERROR_UNKNOWN;
444 pkt->data = av_malloc(pkt->size);
446 return AVERROR_UNKNOWN;
448 frame = avs_library->avs_get_frame(avs->clip, n);
449 error = avs_library->avs_clip_get_error(avs->clip);
451 av_log(s, AV_LOG_ERROR, "%s\n", error);
453 av_freep(&pkt->data);
454 return AVERROR_UNKNOWN;
458 for (i = 0; i < avs->n_planes; i++) {
459 plane = avs->planes[i];
460 src_p = avs_get_read_ptr_p(frame, plane);
461 rowsize = avs_get_row_size_p(frame, plane);
462 planeheight = avs_get_height_p(frame, plane);
463 pitch = avs_get_pitch_p(frame, plane);
466 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
467 src_p = src_p + (planeheight - 1) * pitch;
471 avs_library->avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch, rowsize, planeheight);
472 dst_p += rowsize * planeheight;
475 avs_library->avs_release_video_frame(frame);
479 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt, int discard) {
480 AviSynthContext *avs = s->priv_data;
481 AVRational fps, samplerate;
486 if (avs->curr_sample >= avs->vi->num_audio_samples)
489 fps.num = avs->vi->fps_numerator;
490 fps.den = avs->vi->fps_denominator;
491 samplerate.num = avs->vi->audio_samples_per_second;
494 if (avs_has_video(avs->vi)) {
495 if (avs->curr_frame < avs->vi->num_frames)
496 samples = av_rescale_q(avs->curr_frame, samplerate, fps) - avs->curr_sample;
498 samples = av_rescale_q(1, samplerate, fps);
503 // After seeking, audio may catch up with video.
510 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
511 samples = avs->vi->num_audio_samples - avs->curr_sample;
513 // This must happen even if the stream is discarded to prevent desync.
514 n = avs->curr_sample;
515 avs->curr_sample += samples;
521 pkt->duration = samples;
523 pkt->size = avs_bytes_per_channel_sample(avs->vi) * samples * avs->vi->nchannels;
525 return AVERROR_UNKNOWN;
526 pkt->data = av_malloc(pkt->size);
528 return AVERROR_UNKNOWN;
530 avs_library->avs_get_audio(avs->clip, pkt->data, n, samples);
531 error = avs_library->avs_clip_get_error(avs->clip);
533 av_log(s, AV_LOG_ERROR, "%s\n", error);
535 av_freep(&pkt->data);
536 return AVERROR_UNKNOWN;
541 static av_cold int avisynth_read_header(AVFormatContext *s) {
544 // Calling library must implement a lock for thread-safe opens.
545 if (ret = avpriv_lock_avformat())
548 if (ret = avisynth_open_file(s)) {
549 avpriv_unlock_avformat();
553 avpriv_unlock_avformat();
557 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt) {
558 AviSynthContext *avs = s->priv_data;
564 return AVERROR_UNKNOWN;
566 pkt->destruct = av_destruct_packet;
568 // If either stream reaches EOF, try to read the other one before giving up.
569 avisynth_next_stream(s, &st, pkt, &discard);
570 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
571 ret = avisynth_read_packet_video(s, pkt, discard);
572 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
573 avisynth_next_stream(s, &st, pkt, &discard);
574 return avisynth_read_packet_audio(s, pkt, discard);
578 ret = avisynth_read_packet_audio(s, pkt, discard);
579 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
580 avisynth_next_stream(s, &st, pkt, &discard);
581 return avisynth_read_packet_video(s, pkt, discard);
587 static av_cold int avisynth_read_close(AVFormatContext *s) {
588 if (avpriv_lock_avformat())
589 return AVERROR_UNKNOWN;
591 avisynth_context_destroy(s->priv_data);
592 avpriv_unlock_avformat();
596 static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
597 AviSynthContext *avs = s->priv_data;
599 AVRational fps, samplerate;
602 return AVERROR_UNKNOWN;
604 fps = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
605 samplerate = (AVRational) {avs->vi->audio_samples_per_second, 1};
607 st = s->streams[stream_index];
608 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
609 // AviSynth frame counts are signed int.
610 if ((timestamp >= avs->vi->num_frames) || (timestamp > INT_MAX) || (timestamp < 0))
612 avs->curr_frame = timestamp;
613 if (avs_has_audio(avs->vi))
614 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
616 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
618 // Force frame granularity for seeking.
619 if (avs_has_video(avs->vi)) {
620 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
621 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
623 avs->curr_sample = timestamp;
630 AVInputFormat ff_avisynth_demuxer = {
632 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
633 .priv_data_size = sizeof(AviSynthContext),
634 .read_header = avisynth_read_header,
635 .read_packet = avisynth_read_packet,
636 .read_close = avisynth_read_close,
637 .read_seek = avisynth_read_seek,