FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
avisynth.c
Go to the documentation of this file.
1 /*
2  * Avi/AvxSynth support
3  * Copyright (c) 2012 AvxSynth Team.
4  *
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.
10  *
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.
15  *
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
19  */
20 
21 #include "avformat.h"
22 #include "internal.h"
23 #include "libavcodec/internal.h"
24 
25 // Enable function pointer definitions for runtime loading.
26 #define AVSC_NO_DECLSPEC
27 
28 // Shut up ffmpeg error messages.
29 // avisynth_c.h contains inline functions that call these functions.
30 #undef malloc
31 #undef free
32 #undef printf
33 
34 // Platform-specific directives for AviSynth vs AvxSynth.
35 #ifdef _WIN32
36  #include <windows.h>
37  #undef EXTERN_C
39  #define AVISYNTH_LIB "avisynth"
40 #else
41  #include <dlfcn.h>
43  #if defined (__APPLE__)
44  #define AVISYNTH_LIB "libavxsynth.dylib"
45  #else
46  #define AVISYNTH_LIB "libavxsynth.so"
47  #endif
48 
49  #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
50  #define GetProcAddress dlsym
51  #define FreeLibrary dlclose
52 #endif
53 
54 // AvxSynth doesn't have these colorspaces, so disable them
55 #ifndef _WIN32
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
60 #endif
61 
62 typedef struct {
63  void *library;
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
80 
84  const AVS_VideoInfo *vi;
85 
86  // avisynth_read_packet_video() iterates over this.
87  int n_planes;
88  const int *planes;
89 
92  int64_t curr_sample;
93 
94  int error;
95 
96  // Linked list pointers.
98 };
99 typedef struct AviSynthContext AviSynthContext;
100 
101 static const int avs_planes_packed[1] = {0};
102 static const int avs_planes_grey[1] = {AVS_PLANAR_Y};
104 
105 // A conflict between C++ global objects, atexit, and dynamic loading requires
106 // us to register our own atexit handler to prevent double freeing.
108 static int avs_atexit_called = 0;
109 
110 // Linked list of AviSynthContexts. An atexit handler destroys this list.
112 
113 static av_cold void avisynth_atexit_handler(void);
114 
115 static av_cold int avisynth_load_library(void) {
116  avs_library = av_mallocz(sizeof(AviSynthLibrary));
117  if (!avs_library)
118  return AVERROR_UNKNOWN;
119 
120  avs_library->library = LoadLibrary(AVISYNTH_LIB);
121  if (!avs_library->library)
122  goto init_fail;
123 
124 #define LOAD_AVS_FUNC(name, continue_on_fail) \
125 { \
126  avs_library->name = (void*)GetProcAddress(avs_library->library, #name); \
127  if(!continue_on_fail && !avs_library->name) \
128  goto fail; \
129 }
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);
143 #undef LOAD_AVS_FUNC
144 
145  atexit(avisynth_atexit_handler);
146  return 0;
147 
148 fail:
149  FreeLibrary(avs_library->library);
150 init_fail:
151  av_freep(&avs_library);
152  return AVERROR_UNKNOWN;
153 }
154 
155 // Note that avisynth_context_create and avisynth_context_destroy
156 // do not allocate or free the actual context! That is taken care of
157 // by libavformat.
160  int ret;
161 
162  if (!avs_library) {
163  if (ret = avisynth_load_library())
164  return ret;
165  }
166 
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);
170  if (error) {
171  av_log(s, AV_LOG_ERROR, "%s\n", error);
172  return AVERROR_UNKNOWN;
173  }
174  }
175 
176  if (!avs_ctx_list) {
177  avs_ctx_list = avs;
178  } else {
179  avs->next = avs_ctx_list;
180  avs_ctx_list = avs;
181  }
182 
183  return 0;
184 }
185 
187  if (avs_atexit_called)
188  return;
189 
190  if (avs == avs_ctx_list) {
191  avs_ctx_list = avs->next;
192  } else {
194  while (prev->next != avs)
195  prev = prev->next;
196  prev->next = avs->next;
197  }
198 
199  if (avs->clip) {
200  avs_library->avs_release_clip(avs->clip);
201  avs->clip = NULL;
202  }
203  if (avs->env) {
204  avs_library->avs_delete_script_environment(avs->env);
205  avs->env = NULL;
206  }
207 }
208 
209 static av_cold void avisynth_atexit_handler(void) {
211 
212  while (avs) {
213  AviSynthContext *next = avs->next;
215  avs = next;
216  }
217  FreeLibrary(avs_library->library);
218  av_freep(&avs_library);
219 
220  avs_atexit_called = 1;
221 }
222 
223 // Create AVStream from audio and video data.
225  AviSynthContext *avs = s->priv_data;
226  int planar = 0; // 0: packed, 1: YUV, 2: Y8
227 
230  st->codec->width = avs->vi->width;
231  st->codec->height = avs->vi->height;
232 
233  st->time_base = (AVRational) {avs->vi->fps_denominator, avs->vi->fps_numerator};
235  st->start_time = 0;
236  st->duration = avs->vi->num_frames;
237  st->nb_frames = avs->vi->num_frames;
238 
239  switch (avs->vi->pixel_type) {
240 #ifdef _WIN32
241  case AVS_CS_YV24:
243  planar = 1;
244  break;
245  case AVS_CS_YV16:
247  planar = 1;
248  break;
249  case AVS_CS_YV411:
251  planar = 1;
252  break;
253  case AVS_CS_Y8:
255  planar = 2;
256  break;
257 #endif
258  case AVS_CS_BGR24:
260  break;
261  case AVS_CS_BGR32:
263  break;
264  case AVS_CS_YUY2:
266  break;
267  case AVS_CS_YV12:
269  planar = 1;
270  break;
271  case AVS_CS_I420: // Is this even used anywhere?
273  planar = 1;
274  break;
275  default:
276  av_log(s, AV_LOG_ERROR, "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
277  avs->error = 1;
278  return AVERROR_UNKNOWN;
279  }
280 
281  switch (planar) {
282  case 2: // Y8
283  avs->n_planes = 1;
284  avs->planes = avs_planes_grey;
285  break;
286  case 1: // YUV
287  avs->n_planes = 3;
288  avs->planes = avs_planes_yuv;
289  break;
290  default:
291  avs->n_planes = 1;
292  avs->planes = avs_planes_packed;
293  }
294  return 0;
295 }
296 
298  AviSynthContext *avs = s->priv_data;
299 
302  st->codec->channels = avs->vi->nchannels;
303  st->time_base = (AVRational) {1, avs->vi->audio_samples_per_second};
304 
305  switch (avs->vi->sample_type) {
306  case AVS_SAMPLE_INT8:
308  break;
309  case AVS_SAMPLE_INT16:
311  break;
312  case AVS_SAMPLE_INT24:
314  break;
315  case AVS_SAMPLE_INT32:
317  break;
318  case AVS_SAMPLE_FLOAT:
320  break;
321  default:
322  av_log(s, AV_LOG_ERROR, "unknown AviSynth sample type %d\n", avs->vi->sample_type);
323  avs->error = 1;
324  return AVERROR_UNKNOWN;
325  }
326  return 0;
327 }
328 
330  AviSynthContext *avs = s->priv_data;
331  AVStream *st;
332  int ret;
333  int id = 0;
334 
335  if (avs_has_video(avs->vi)) {
336  st = avformat_new_stream(s, NULL);
337  if (!st)
338  return AVERROR_UNKNOWN;
339  st->id = id++;
340  if (ret = avisynth_create_stream_video(s, st))
341  return ret;
342  }
343  if (avs_has_audio(avs->vi)) {
344  st = avformat_new_stream(s, NULL);
345  if (!st)
346  return AVERROR_UNKNOWN;
347  st->id = id++;
348  if (ret = avisynth_create_stream_audio(s, st))
349  return ret;
350  }
351  return 0;
352 }
353 
356  AVS_Value arg, val;
357  int ret;
358 #ifdef _WIN32
359  char filename_ansi[MAX_PATH * 4];
360  wchar_t filename_wc[MAX_PATH * 4];
361 #endif
362 
364  return ret;
365 
366 #ifdef _WIN32
367  // Convert UTF-8 to ANSI code page
368  MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
369  WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi, MAX_PATH * 4, NULL, NULL);
370  arg = avs_new_value_string(filename_ansi);
371 #else
372  arg = avs_new_value_string(s->filename);
373 #endif
374  val = avs_library->avs_invoke(avs->env, "Import", arg, 0);
375  if (avs_is_error(val)) {
376  av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
378  goto fail;
379  }
380  if (!avs_is_clip(val)) {
381  av_log(s, AV_LOG_ERROR, "%s\n", "AviSynth script did not return a clip");
383  goto fail;
384  }
385 
386  avs->clip = avs_library->avs_take_clip(val, avs->env);
387  avs->vi = avs_library->avs_get_video_info(avs->clip);
388 
389  // Release the AVS_Value as it will go out of scope.
390  avs_library->avs_release_value(val);
391 
392  if (ret = avisynth_create_stream(s))
393  goto fail;
394 
395  return 0;
396 
397 fail:
399  return ret;
400 }
401 
402 static void avisynth_next_stream(AVFormatContext *s, AVStream **st, AVPacket *pkt, int *discard) {
403  AviSynthContext *avs = s->priv_data;
404 
405  pkt->stream_index = avs->curr_stream++;
406  avs->curr_stream %= s->nb_streams;
407 
408  *st = s->streams[pkt->stream_index];
409  if ((*st)->discard == AVDISCARD_ALL)
410  *discard = 1;
411  else
412  *discard = 0;
413 
414  return;
415 }
416 
417 // Copy AviSynth clip data into an AVPacket.
419  AviSynthContext *avs = s->priv_data;
421  unsigned char *dst_p;
422  const unsigned char *src_p;
423  int n, i, plane, rowsize, planeheight, pitch, bits;
424  const char *error;
425 
426  if (avs->curr_frame >= avs->vi->num_frames)
427  return AVERROR_EOF;
428 
429  // This must happen even if the stream is discarded to prevent desync.
430  n = avs->curr_frame++;
431  if (discard)
432  return 0;
433 
434  pkt->pts = n;
435  pkt->dts = n;
436  pkt->duration = 1;
437 
438  // Define the bpp values for the new AviSynth 2.6 colorspaces
439  if (avs_is_yv24(avs->vi)) {
440  bits = 24;
441  } else if (avs_is_yv16(avs->vi)) {
442  bits = 16;
443  } else if (avs_is_yv411(avs->vi)) {
444  bits = 12;
445  } else if (avs_is_y8(avs->vi)) {
446  bits = 8;
447  } else {
448  bits = avs_bits_per_pixel(avs->vi);
449  }
450 
451  // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.
452  pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;
453  if (!pkt->size)
454  return AVERROR_UNKNOWN;
455  pkt->data = av_malloc(pkt->size);
456  if (!pkt->data)
457  return AVERROR_UNKNOWN;
458 
459  frame = avs_library->avs_get_frame(avs->clip, n);
460  error = avs_library->avs_clip_get_error(avs->clip);
461  if (error) {
462  av_log(s, AV_LOG_ERROR, "%s\n", error);
463  avs->error = 1;
464  av_freep(&pkt->data);
465  return AVERROR_UNKNOWN;
466  }
467 
468  dst_p = pkt->data;
469  for (i = 0; i < avs->n_planes; i++) {
470  plane = avs->planes[i];
471  src_p = avs_get_read_ptr_p(frame, plane);
472  rowsize = avs_get_row_size_p(frame, plane);
473  planeheight = avs_get_height_p(frame, plane);
474  pitch = avs_get_pitch_p(frame, plane);
475 
476  // Flip RGB video.
477  if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
478  src_p = src_p + (planeheight - 1) * pitch;
479  pitch = -pitch;
480  }
481 
482  avs_library->avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch, rowsize, planeheight);
483  dst_p += rowsize * planeheight;
484  }
485 
486  avs_library->avs_release_video_frame(frame);
487  return 0;
488 }
489 
491  AviSynthContext *avs = s->priv_data;
492  AVRational fps, samplerate;
493  int samples;
494  int64_t n;
495  const char *error;
496 
497  if (avs->curr_sample >= avs->vi->num_audio_samples)
498  return AVERROR_EOF;
499 
500  fps.num = avs->vi->fps_numerator;
501  fps.den = avs->vi->fps_denominator;
502  samplerate.num = avs->vi->audio_samples_per_second;
503  samplerate.den = 1;
504 
505  if (avs_has_video(avs->vi)) {
506  if (avs->curr_frame < avs->vi->num_frames)
507  samples = av_rescale_q(avs->curr_frame, samplerate, fps) - avs->curr_sample;
508  else
509  samples = av_rescale_q(1, samplerate, fps);
510  } else {
511  samples = 1000;
512  }
513 
514  // After seeking, audio may catch up with video.
515  if (samples <= 0) {
516  pkt->size = 0;
517  pkt->data = NULL;
518  return 0;
519  }
520 
521  if (avs->curr_sample + samples > avs->vi->num_audio_samples)
522  samples = avs->vi->num_audio_samples - avs->curr_sample;
523 
524  // This must happen even if the stream is discarded to prevent desync.
525  n = avs->curr_sample;
526  avs->curr_sample += samples;
527  if (discard)
528  return 0;
529 
530  pkt->pts = n;
531  pkt->dts = n;
532  pkt->duration = samples;
533 
534  pkt->size = avs_bytes_per_channel_sample(avs->vi) * samples * avs->vi->nchannels;
535  if (!pkt->size)
536  return AVERROR_UNKNOWN;
537  pkt->data = av_malloc(pkt->size);
538  if (!pkt->data)
539  return AVERROR_UNKNOWN;
540 
541  avs_library->avs_get_audio(avs->clip, pkt->data, n, samples);
542  error = avs_library->avs_clip_get_error(avs->clip);
543  if (error) {
544  av_log(s, AV_LOG_ERROR, "%s\n", error);
545  avs->error = 1;
546  av_freep(&pkt->data);
547  return AVERROR_UNKNOWN;
548  }
549  return 0;
550 }
551 
553  int ret;
554 
555  // Calling library must implement a lock for thread-safe opens.
556  if (ret = avpriv_lock_avformat())
557  return ret;
558 
559  if (ret = avisynth_open_file(s)) {
561  return ret;
562  }
563 
565  return 0;
566 }
567 
569  AviSynthContext *avs = s->priv_data;
570  AVStream *st;
571  int discard = 0;
572  int ret;
573 
574  if (avs->error)
575  return AVERROR_UNKNOWN;
576 
577  pkt->destruct = av_destruct_packet;
578 
579  // If either stream reaches EOF, try to read the other one before giving up.
580  avisynth_next_stream(s, &st, pkt, &discard);
581  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
582  ret = avisynth_read_packet_video(s, pkt, discard);
583  if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
584  avisynth_next_stream(s, &st, pkt, &discard);
585  return avisynth_read_packet_audio(s, pkt, discard);
586  }
587  return ret;
588  } else {
589  ret = avisynth_read_packet_audio(s, pkt, discard);
590  if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
591  avisynth_next_stream(s, &st, pkt, &discard);
592  return avisynth_read_packet_video(s, pkt, discard);
593  }
594  return ret;
595  }
596 }
597 
599  if (avpriv_lock_avformat())
600  return AVERROR_UNKNOWN;
601 
604  return 0;
605 }
606 
607 static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
608  AviSynthContext *avs = s->priv_data;
609  AVStream *st;
610  AVRational fps, samplerate;
611 
612  if (avs->error)
613  return AVERROR_UNKNOWN;
614 
615  fps = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
616  samplerate = (AVRational) {avs->vi->audio_samples_per_second, 1};
617 
618  st = s->streams[stream_index];
619  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
620  // AviSynth frame counts are signed int.
621  if ((timestamp >= avs->vi->num_frames) || (timestamp > INT_MAX) || (timestamp < 0))
622  return AVERROR_EOF;
623  avs->curr_frame = timestamp;
624  if (avs_has_audio(avs->vi))
625  avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
626  } else {
627  if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
628  return AVERROR_EOF;
629  // Force frame granularity for seeking.
630  if (avs_has_video(avs->vi)) {
631  avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
632  avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
633  } else {
634  avs->curr_sample = timestamp;
635  }
636  }
637 
638  return 0;
639 }
640 
642  .name = "avisynth",
643  .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
644  .priv_data_size = sizeof(AviSynthContext),
649  .extensions = "avs",
650 };