Update to MPlayer SVN rev 29473 and FFmpeg SVN rev 19572.
[vaapi:athaifas-mplayer.git] / mencoder.c
1 #define VCODEC_COPY 0
2 #define VCODEC_FRAMENO 1
3 // real codecs:
4 #define VCODEC_LIBAVCODEC 4
5 #define VCODEC_VFW 7
6 #define VCODEC_LIBDV 8
7 #define VCODEC_XVID 9
8 #define VCODEC_QTVIDEO 10
9 #define VCODEC_NUV 11
10 #define VCODEC_RAW 12
11 #define VCODEC_X264 13
12
13 #define ACODEC_COPY 0
14 #define ACODEC_PCM 1
15 #define ACODEC_VBRMP3 2
16 #define ACODEC_NULL 3
17 #define ACODEC_LAVC 4
18 #define ACODEC_TOOLAME 5
19 #define ACODEC_FAAC 6
20 #define ACODEC_TWOLAME 7
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <signal.h>
26 #include "config.h"
27
28 #ifdef __MINGW32__
29 #define        SIGHUP 1
30 #define        SIGQUIT 3
31 #define        SIGPIPE 13
32 #endif
33 #if defined(__MINGW32__) || defined(__CYGWIN__)
34 #include <windows.h>
35 #endif
36
37 #include <sys/time.h>
38
39 #include "mp_msg.h"
40 #include "help_mp.h"
41
42 #include "codec-cfg.h"
43 #include "m_option.h"
44 #include "m_config.h"
45 #include "parser-mecmd.h"
46 #include "parser-cfg.h"
47
48 #include "get_path.h"
49
50 #include "stream/stream.h"
51 #include "libmpdemux/demuxer.h"
52 #include "libmpdemux/stheader.h"
53 #include "libmpdemux/mp3_hdr.h"
54 #include "libmpdemux/muxer.h"
55
56
57 #include "libvo/video_out.h"
58
59 #include "libaf/af_format.h"
60
61 #include "libmpcodecs/mp_image.h"
62 #include "libmpcodecs/dec_audio.h"
63 #include "libmpcodecs/dec_video.h"
64 #include "libmpcodecs/vf.h"
65 #include "libmpcodecs/vd.h"
66
67 // for MPEGLAYER3WAVEFORMAT:
68 #include "libmpdemux/ms_hdr.h"
69
70 #include <inttypes.h>
71
72 #include "libvo/fastmemcpy.h"
73
74 #include "osdep/timer.h"
75
76 #ifdef CONFIG_DVDREAD
77 #include "stream/stream_dvd.h"
78 #endif
79
80 #include "stream/stream_dvdnav.h"
81 #include "libavcodec/avcodec.h"
82
83 #include "libmpcodecs/ae.h"
84 int vo_doublebuffering=0;
85 int vo_directrendering=0;
86 int vo_config_count=1;
87 int forced_subs_only=0;
88
89 //--------------------------
90
91 // cache2:
92 int stream_cache_size=-1;
93 #ifdef CONFIG_STREAM_CACHE
94 extern int cache_fill_status;
95
96 float stream_cache_min_percent=20.0;
97 float stream_cache_seek_min_percent=50.0;
98 #else
99 #define cache_fill_status 0
100 #endif
101
102 int audio_id=-1;
103 int video_id=-1;
104 int dvdsub_id=-2;
105 int vobsub_id=-1;
106 char* audio_lang=NULL;
107 char* dvdsub_lang=NULL;
108 static char* spudec_ifo=NULL;
109
110 static char** audio_codec_list=NULL;  // override audio codec
111 static char** video_codec_list=NULL;  // override video codec
112 static char** audio_fm_list=NULL;     // override audio codec family
113 static char** video_fm_list=NULL;     // override video codec family
114 extern char *demuxer_name; // override demuxer
115 extern char *audio_demuxer_name; // override audio demuxer
116 extern char *sub_demuxer_name; // override sub demuxer
117
118 static int out_audio_codec=-1;
119 static int out_video_codec=-1;
120
121 int out_file_format=MUXER_TYPE_AVI;     // default to AVI
122
123 // audio stream skip/resync functions requires only for seeking.
124 // (they should be implemented in the audio codec layer)
125 //void skip_audio_frame(sh_audio_t *sh_audio){}
126 //void resync_audio_stream(sh_audio_t *sh_audio){}
127
128 int quiet=0;
129 double video_time_usage=0;
130 double vout_time_usage=0;
131 double max_video_time_usage=0;
132 double max_vout_time_usage=0;
133 double cur_video_time_usage=0;
134 double cur_vout_time_usage=0;
135 int benchmark=0;
136
137 #include "osdep/priority.h"
138
139 // A-V sync:
140 int delay_corrected=1;
141 static float default_max_pts_correction=-1;//0.01f;
142 static float max_pts_correction=0;//default_max_pts_correction;
143 static float c_total=0;
144
145 static float audio_preload=0.5;
146 static float audio_delay_fix=0.0;
147 static float audio_delay=0.0;
148 static int ignore_start=0;
149 static int audio_density=2;
150
151 double force_fps=0;
152 static double force_ofps=0; // set to 24 for inverse telecine
153 static int skip_limit=-1;
154 float playback_speed=1.0;
155
156 static int force_srate=0;
157 static int audio_output_format=0;
158
159 char *vobsub_out=NULL;
160 unsigned int vobsub_out_index=0;
161 char *vobsub_out_id=NULL;
162
163 char* out_filename=NULL;
164
165 char *force_fourcc=NULL;
166 int force_audiofmttag=-1;
167
168 char* passtmpfile="divx2pass.log";
169
170 static int play_n_frames=-1;
171 static int play_n_frames_mf=-1;
172
173 #include "libvo/font_load.h"
174 #include "libvo/sub.h"
175
176 // sub:
177 char *font_name=NULL;
178 char *sub_font_name=NULL;
179 extern int font_fontconfig;
180 float font_factor=0.75;
181 char **sub_name=NULL;
182 float sub_delay=0;
183 float sub_fps=0;
184 int   sub_auto = 0;
185 int   subcc_enabled=0;
186 int   suboverlap_enabled = 1;
187
188 int auto_expand=1;
189 int encode_duplicates=1;
190
191 // infos are empty by default
192 char *info_name=NULL;
193 char *info_artist=NULL;
194 char *info_genre=NULL;
195 char *info_subject=NULL;
196 char *info_copyright=NULL;
197 char *info_sourceform=NULL;
198 char *info_comment=NULL;
199
200 // Needed by libmpcodecs vf_vo.c
201 int config_video_out(const vo_functions_t *vo, uint32_t width, uint32_t height,
202                      uint32_t d_width, uint32_t d_height, uint32_t flags,
203                      char *title, uint32_t format) {
204   return 1;
205 }
206 // Needed by libmpdemux.
207 int mp_input_check_interrupt(int time) {
208   usec_sleep(time);
209   return 0;
210 }
211 // Needed by getch2
212 void mplayer_put_key(int code)
213 {
214 }
215
216 #include "libass/ass.h"
217 #include "libass/ass_mp.h"
218 char *current_module;
219 #include "mpcommon.h"
220
221 //char *out_audio_codec=NULL; // override audio codec
222 //char *out_video_codec=NULL; // override video codec
223
224 //#include "libmpeg2/mpeg2.h"
225 //#include "libmpeg2/mpeg2_internal.h"
226
227 //static int vo_w=0, vo_h=0;
228
229 //-------------------------- config stuff:
230
231 m_config_t* mconfig;
232
233 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
234
235 static int cfg_include(m_option_t *conf, char *filename){
236         return m_config_parse_config_file(mconfig, filename);
237 }
238
239 static double seek_to_sec;
240 static off_t seek_to_byte=0;
241
242 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
243
244 static char * frameno_filename=NULL;
245
246 //static uint8_t* flip_upside_down(uint8_t* dst, const uint8_t* src, int width, int height);
247
248 typedef struct {
249     unsigned char* start;
250     int in_size;
251     float frame_time;
252     int already_read;
253 } s_frame_data;
254
255 /// Returns a_pts
256 static float calc_a_pts(demux_stream_t *d_audio);
257 /** \brief Seeks audio forward to pts by dumping audio packets
258     \return The current audio pts.
259 */
260 static float forward_audio(float pts, demux_stream_t *d_audio, muxer_stream_t* mux_a);
261 /** \brief Seeks slowly by dumping frames.
262     \return 1 for success, 2 for EOF.
263 */
264 static int slowseek(float end_pts, demux_stream_t *d_video, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy, int print_info);
265 /// Deletes audio or video as told by -delay to sync
266 static void fixdelay(demux_stream_t *d_video, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy);
267
268 #include "edl.h"
269 static edl_record_ptr edl_records = NULL; ///< EDL entries memory area
270 static edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
271 static short edl_muted; ///< Stores whether EDL is currently in muted mode.
272 static short edl_seeking; ///< When non-zero, stream is seekable.
273 static short edl_seek_type; ///< When non-zero, frames are discarded instead of seeking.
274 /** \brief Seeks for EDL
275     \return 1 for success, 0 for failure, 2 for EOF.
276 */
277 static int edl_seek(edl_record_ptr next_edl_record, demuxer_t* demuxer, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy);
278
279 #include "cfg-mencoder.h"
280
281 #include "spudec.h"
282 #include "vobsub.h"
283
284 #include "libao2/audio_out.h"
285 /* FIXME */
286 static void mencoder_exit(int level, const char *how)
287 {
288     if (how)
289         mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ExitingHow, how);
290     else
291         mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_Exiting);
292
293     exit(level);
294 }
295
296 static void parse_cfgfiles( m_config_t* conf )
297 {
298   char *conffile;
299   if (!disable_system_conf &&
300       m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mencoder.conf") < 0)
301     mencoder_exit(1,MSGTR_ConfigFileError);
302
303   if (!disable_user_conf) {
304     if ((conffile = get_path("mencoder.conf")) == NULL) {
305       mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_GetpathProblem);
306     } else {
307       if (m_config_parse_config_file(conf, conffile) < 0)
308         mencoder_exit(1,MSGTR_ConfigFileError);
309       free(conffile);
310     }
311   }
312 }
313
314
315 //---------------------------------------------------------------------------
316
317 static int dec_audio(sh_audio_t *sh_audio,unsigned char* buffer,int total){
318     int size=0;
319     int at_eof=0;
320     while(size<total && !at_eof){
321         int len=total-size;
322                 if(len>MAX_OUTBURST) len=MAX_OUTBURST;
323                 if (decode_audio(sh_audio, len) < 0) at_eof=1;
324                 if(len>sh_audio->a_out_buffer_len) len=sh_audio->a_out_buffer_len;
325                 fast_memcpy(buffer+size,sh_audio->a_out_buffer,len);
326                 sh_audio->a_out_buffer_len-=len; size+=len;
327                 if(sh_audio->a_out_buffer_len>0)
328                     fast_memcpy(sh_audio->a_out_buffer,&sh_audio->a_out_buffer[len],sh_audio->a_out_buffer_len);
329     }
330     return size;
331 }
332
333 //---------------------------------------------------------------------------
334
335 // this function returns the absoloute time for which MEncoder will switch files or move in the file.
336 // so audio can be cut correctly. -1 if there is no limit.
337 static float stop_time(demuxer_t* demuxer, muxer_stream_t* mux_v);
338
339 static volatile int at_eof=0;
340 static volatile int interrupted=0;
341
342 static void exit_sighandler(int x){
343     at_eof=1;
344     interrupted=2; /* 1 means error */
345 }
346
347 static muxer_t* muxer=NULL;
348
349 void print_wave_header(WAVEFORMATEX *h, int verbose_level);
350
351 int main(int argc,char* argv[]){
352
353 stream_t* stream=NULL;
354 stream_t* ostream=NULL;
355 demuxer_t* demuxer=NULL;
356 stream_t* stream2=NULL;
357 demuxer_t* demuxer2=NULL;
358 demux_stream_t *d_audio=NULL;
359 demux_stream_t *d_video=NULL;
360 demux_stream_t *d_dvdsub=NULL;
361 sh_audio_t *sh_audio=NULL;
362 sh_video_t *sh_video=NULL;
363 int file_format=DEMUXER_TYPE_UNKNOWN;
364 int i=DEMUXER_TYPE_UNKNOWN;
365 void *vobsub_writer=NULL;
366 s_frame_data frame_data = { .start = NULL, .in_size = 0, .frame_time = 0., .already_read = 0 };
367
368 uint32_t ptimer_start;
369 uint32_t audiorate=0;
370 uint32_t videorate=0;
371 uint32_t audiosamples=1;
372 uint32_t videosamples=1;
373 uint32_t skippedframes=0;
374 uint32_t duplicatedframes=0;
375 uint32_t badframes=0;
376
377 muxer_stream_t* mux_a=NULL;
378 muxer_stream_t* mux_v=NULL;
379 off_t muxer_f_size=0;
380
381 double v_pts_corr=0;
382 double v_timer_corr=0;
383
384 m_entry_t* filelist = NULL;
385 char* filename=NULL;
386
387 int decoded_frameno=0;
388 int next_frameno=-1;
389 int curfile=0;
390 int new_srate=0;
391
392 unsigned int timer_start=0;
393 ao_data_t ao_data = {0,0,0,0,OUTBURST,-1,0};
394
395 audio_encoding_params_t aparams;
396 audio_encoder_t *aencoder = NULL;
397
398 user_correct_pts = 0;
399
400   mp_msg_init();
401
402   // Create the config context and register the options
403   mconfig = m_config_new();
404   m_config_register_options(mconfig,mencoder_opts);
405
406   // Preparse the command line
407   m_config_preparse_command_line(mconfig,argc,argv);
408
409   print_version("MEncoder");
410
411 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
412   set_path_env();
413 #endif
414
415   InitTimer();
416
417 // check codec.conf
418 if(!codecs_file || !parse_codec_cfg(codecs_file)){
419   if(!parse_codec_cfg(get_path("codecs.conf"))){
420     if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
421       if(!parse_codec_cfg(NULL)){
422         mencoder_exit(1,NULL);
423       }
424       mp_msg(MSGT_MENCODER,MSGL_V,MSGTR_BuiltinCodecsConf);
425     }
426   }
427 }
428
429  parse_cfgfiles(mconfig);
430  filelist = m_config_parse_me_command_line(mconfig, argc, argv);
431  if(!filelist) mencoder_exit(1, MSGTR_ErrorParsingCommandLine);
432
433 {
434         char *extension;
435
436         if (!out_filename) mencoder_exit(1,MSGTR_MissingOutputFilename);
437         extension=strrchr(out_filename,'.');
438         if (extension != NULL && strlen(extension) > 3 && strlen(extension) < 6)
439         {
440                 extension++;
441
442                 switch (out_file_format)
443                 {
444                         case MUXER_TYPE_AVI:
445                         if (strcasecmp(extension,"avi"))
446                                 mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_MencoderWrongFormatAVI);
447                         break;
448
449                         case MUXER_TYPE_MPEG:
450                         if (strcasecmp(extension,"mpg") &&
451                                 strcasecmp(extension,"mpeg") &&
452                                 strcasecmp(extension,"vob"))
453                                 mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_MencoderWrongFormatMPG);
454                         break;
455                 }
456         }
457 }
458  /* Display what configure line was used */
459  mp_msg(MSGT_MENCODER, MSGL_V, "Configuration: " CONFIGURATION "\n");
460
461
462 if (frameno_filename) {
463   stream2=open_stream(frameno_filename,0,&i);
464   if(stream2){
465     demuxer2=demux_open(stream2,DEMUXER_TYPE_AVI,-1,-1,-2,NULL);
466     if(demuxer2) mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_UsingPass3ControlFile, frameno_filename);
467     else mp_msg(MSGT_DEMUXER,MSGL_ERR,MSGTR_FormatNotRecognized);
468   }
469 }
470
471 #ifdef CONFIG_PRIORITY
472   set_priority();
473 #endif
474
475 // check font
476 #ifdef CONFIG_FREETYPE
477   init_freetype();
478 #endif
479 #ifdef CONFIG_FONTCONFIG
480   if(font_fontconfig <= 0)
481   {
482 #endif
483 #ifdef CONFIG_BITMAP_FONT
484   if(font_name){
485        vo_font=read_font_desc(font_name,font_factor,verbose>1);
486        if(!vo_font) mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantLoadFont,font_name);
487   } else {
488       // try default:
489        vo_font=read_font_desc(get_path("font/font.desc"),font_factor,verbose>1);
490        if(!vo_font)
491          vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
492   }
493 #endif
494 #ifdef CONFIG_FONTCONFIG
495   }
496 #endif
497
498   vo_init_osd();
499
500   /* HACK, for some weird reason, push() has to be called twice,
501      otherwise options are not saved correctly */
502   m_config_push(mconfig);
503 play_next_file:
504   m_config_push(mconfig);
505   m_entry_set_options(mconfig,&filelist[curfile]);
506   filename = filelist[curfile].name;
507
508   if(!filename){
509         mp_msg(MSGT_CPLAYER, MSGL_FATAL, MSGTR_MissingFilename);
510         mencoder_exit(1,NULL);
511   }
512   stream=open_stream(filename,0,&file_format);
513
514   if(!stream){
515         mp_msg(MSGT_CPLAYER, MSGL_FATAL, MSGTR_CannotOpenFile_Device);
516         mencoder_exit(1,NULL);
517   }
518
519   mp_msg(MSGT_CPLAYER, MSGL_INFO, MSGTR_OpenedStream, file_format, (int)(stream->start_pos), (int)(stream->end_pos));
520
521 #ifdef CONFIG_DVDREAD
522 if(stream->type==STREAMTYPE_DVD){
523   if(audio_lang && audio_id==-1) audio_id=dvd_aid_from_lang(stream,audio_lang);
524   if(dvdsub_lang && dvdsub_id==-2) dvdsub_id=dvd_sid_from_lang(stream,dvdsub_lang);
525 }
526 #endif
527
528 #ifdef CONFIG_DVDNAV
529 if(stream->type==STREAMTYPE_DVDNAV){
530   if(audio_lang && audio_id==-1) audio_id=mp_dvdnav_aid_from_lang(stream,audio_lang);
531   if(dvdsub_lang && dvdsub_id==-2) dvdsub_id=mp_dvdnav_sid_from_lang(stream,dvdsub_lang);
532 }
533 #endif
534
535   stream->start_pos+=seek_to_byte;
536
537   if(stream_cache_size>0) stream_enable_cache(stream,stream_cache_size*1024,0,0);
538
539   if(demuxer2) audio_id=-2; /* do NOT read audio packets... */
540
541   //demuxer=demux_open(stream,file_format,video_id,audio_id,dvdsub_id);
542   demuxer=demux_open(stream,file_format,audio_id,video_id,dvdsub_id,filename);
543   if(!demuxer){
544     mp_msg(MSGT_DEMUXER, MSGL_FATAL, MSGTR_FormatNotRecognized);
545     mp_msg(MSGT_DEMUXER, MSGL_FATAL, MSGTR_CannotOpenDemuxer);
546         mencoder_exit(1,NULL);
547   }
548
549   select_audio(demuxer, audio_id, audio_lang);
550
551   if (dvdsub_id < 0 && dvdsub_lang)
552     dvdsub_id = demuxer_sub_track_by_lang(demuxer, dvdsub_lang);
553
554   if (dvdsub_id < 0)
555     dvdsub_id = demuxer_default_sub_track(demuxer);
556
557   for (i = 0; i < MAX_S_STREAMS; i++) {
558     sh_sub_t *sh = demuxer->s_streams[i];
559     if (sh && sh->sid == dvdsub_id) {
560       demuxer->sub->id = i;
561       demuxer->sub->sh = sh;
562       break;
563     }
564   }
565
566   if(dvd_chapter>1) {
567     float pts;
568     if (demuxer_seek_chapter(demuxer, dvd_chapter-1, 1, &pts, NULL, NULL) >= 0 && pts > -1.0)
569       seek_to_sec = pts;
570   }
571
572 d_audio=demuxer2 ? demuxer2->audio : demuxer->audio;
573 d_video=demuxer->video;
574 d_dvdsub=demuxer->sub;
575 sh_audio=d_audio->sh;
576 sh_video=d_video->sh;
577
578   if(!sh_video)
579   {
580         mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_VideoStreamRequired);
581         mencoder_exit(1,NULL);
582   }
583
584   if(!video_read_properties(sh_video)){
585       mp_msg(MSGT_CPLAYER, MSGL_FATAL, MSGTR_CannotReadVideoProperties);
586       mencoder_exit(1,NULL);
587   }
588
589   mp_msg(MSGT_MENCODER,MSGL_INFO, MSGTR_FilefmtFourccSizeFpsFtime,
590    demuxer->file_format,sh_video->format, sh_video->disp_w,sh_video->disp_h,
591    sh_video->fps,sh_video->frametime
592   );
593
594   if(force_fps){
595     sh_video->fps=force_fps;
596     sh_video->frametime=1.0f/sh_video->fps;
597     mp_msg(MSGT_MENCODER,MSGL_INFO,MSGTR_ForcingInputFPS, sh_video->fps);
598   }
599
600   if(sh_audio && out_audio_codec<0){
601     if(audio_id==-2)
602         mp_msg(MSGT_MENCODER,MSGL_ERR,MSGTR_DemuxerDoesntSupportNosound);
603     mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_NoAudioEncoderSelected);
604     mencoder_exit(1,NULL);
605   }
606   if(sh_video && out_video_codec<0){
607     mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_NoVideoEncoderSelected);
608     mencoder_exit(1,NULL);
609   }
610
611 if(sh_audio && (out_audio_codec || seek_to_sec || !sh_audio->wf || playback_speed != 1.0)){
612   // Go through the codec.conf and find the best codec...
613   mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
614   if(!init_best_audio_codec(sh_audio,audio_codec_list,audio_fm_list)){
615     sh_audio=d_audio->sh=NULL; // failed to init :(
616   }
617   mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
618 }
619
620   if (sh_audio) {
621     new_srate = sh_audio->samplerate;
622     if (playback_speed != 1.0) {
623         new_srate *= playback_speed;
624         // limits are taken from libaf/af_resample.c
625         if (new_srate < 8000) new_srate = 8000;
626         if (new_srate > 192000) new_srate = 192000;
627         playback_speed = (float)new_srate / (float)sh_audio->samplerate;
628     }
629   }
630
631 // after reading video params we should load subtitles because
632 // we know fps so now we can adjust subtitles time to ~6 seconds AST
633 // check .sub
634 //  current_module="read_subtitles_file";
635   if(sub_name && sub_name[0]){
636     subdata=sub_read_file(sub_name[0], sh_video->fps);
637     if(!subdata) mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantLoadSub,sub_name[0]);
638   } else
639   if(sub_auto && filename) { // auto load sub file ...
640     char **tmp = NULL;
641     int i = 0;
642     char *psub = get_path( "sub/" );
643     tmp = sub_filenames((psub ? psub : ""), filename);
644     free(psub);
645     subdata=sub_read_file(tmp[0], sh_video->fps);
646     while (tmp[i])
647       free(tmp[i++]);
648     free(tmp);
649   }
650
651 // set up video encoder:
652
653 if (!curfile) { // curfile is non zero when a second file is opened
654 if (vobsub_out) {
655     unsigned int palette[16], width, height;
656     unsigned char tmp[3] = { 0, 0, 0 };
657     if (spudec_ifo && vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, dvdsub_id, tmp) >= 0)
658         vobsub_writer = vobsub_out_open(vobsub_out, palette, sh_video->disp_w, sh_video->disp_h,
659                                         vobsub_out_id?vobsub_out_id:(char *)tmp, vobsub_out_index);
660 #ifdef CONFIG_DVDREAD
661     if (vobsub_writer == NULL) {
662         char tmp[3];
663         if (vobsub_out_id == NULL && stream->type == STREAMTYPE_DVD) {
664             int i;
665             dvd_priv_t *dvd = (dvd_priv_t*)stream->priv;
666             for (i = 0; i < dvd->nr_of_subtitles; ++i)
667                 if (dvd->subtitles[i].id == dvdsub_id) {
668                     tmp[0] = (dvd->subtitles[i].language >> 8) & 0xff;
669                     tmp[1] = dvd->subtitles[i].language & 0xff;
670                     tmp[2] = 0;
671                     vobsub_out_id = tmp;
672                     break;
673                 }
674         }
675         vobsub_writer=vobsub_out_open(vobsub_out, stream->type==STREAMTYPE_DVD?((dvd_priv_t *)(stream->priv))->cur_pgc->palette:NULL,
676                                       sh_video->disp_w, sh_video->disp_h, vobsub_out_id, vobsub_out_index);
677     }
678 #endif
679 }
680 else {
681 if (spudec_ifo) {
682   unsigned int palette[16], width, height;
683   if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
684     vo_spudec=spudec_new_scaled(palette, sh_video->disp_w, sh_video->disp_h, NULL, 0);
685 }
686 #ifdef CONFIG_DVDREAD
687 if (vo_spudec==NULL) {
688 vo_spudec=spudec_new_scaled(stream->type==STREAMTYPE_DVD?((dvd_priv_t *)(stream->priv))->cur_pgc->palette:NULL,
689                            sh_video->disp_w, sh_video->disp_h, NULL, 0);
690 }
691 #endif
692 if (vo_spudec)
693   spudec_set_forced_subs_only(vo_spudec, forced_subs_only);
694 }
695
696 ostream = open_output_stream(out_filename, 0);
697 if(!ostream) {
698   mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_CannotOpenOutputFile, out_filename);
699   mencoder_exit(1,NULL);
700 }
701
702 muxer=muxer_new_muxer(out_file_format,ostream);
703 if(!muxer) {
704   mp_msg(MSGT_MENCODER, MSGL_FATAL, MSGTR_CannotInitializeMuxer);
705   mencoder_exit(1,NULL);
706 }
707 #if 0
708 //disabled: it horrybly distorts filtered sound
709 if(out_file_format == MUXER_TYPE_MPEG) audio_preload = 0;
710 #endif
711
712 muxer->audio_delay_fix = audio_delay_fix;
713
714 // ============= VIDEO ===============
715
716 mux_v=muxer_new_stream(muxer,MUXER_TYPE_VIDEO);
717
718 mux_v->buffer_size=0x200000; // 2MB
719 mux_v->buffer=malloc(mux_v->buffer_size);
720
721 mux_v->source=sh_video;
722
723 mux_v->h.dwSampleSize=0; // VBR
724 #ifdef CONFIG_LIBAVCODEC
725 {
726     double fps = force_ofps?force_ofps:sh_video->fps*playback_speed;
727     AVRational q= av_d2q(fps, fps*1001+2);
728     mux_v->h.dwScale= q.den;
729     mux_v->h.dwRate = q.num;
730 }
731 #else
732 mux_v->h.dwScale=10000;
733 mux_v->h.dwRate=mux_v->h.dwScale*(force_ofps?force_ofps:sh_video->fps*playback_speed);
734 #endif
735
736 mux_v->codec=out_video_codec;
737
738 mux_v->bih=NULL;
739 }
740 sh_video->codec=NULL;
741 sh_video->vfilter=NULL; // fixme!
742
743 switch(mux_v->codec){
744 case VCODEC_COPY:
745         if (!curfile) {
746                 if (sh_video->bih) {
747                         mux_v->bih=malloc(sh_video->bih->biSize);
748                         memcpy(mux_v->bih, sh_video->bih, sh_video->bih->biSize);
749                 }
750     else
751     {
752         mux_v->bih=calloc(1,sizeof(BITMAPINFOHEADER));
753         mux_v->bih->biSize=sizeof(BITMAPINFOHEADER);
754         mux_v->bih->biWidth=sh_video->disp_w;
755         mux_v->bih->biHeight=sh_video->disp_h;
756         mux_v->bih->biCompression=sh_video->format;
757         mux_v->bih->biPlanes=1;
758         mux_v->bih->biBitCount=24; // FIXME!!!
759         mux_v->bih->biSizeImage=mux_v->bih->biWidth*mux_v->bih->biHeight*(mux_v->bih->biBitCount/8);
760     }
761         }
762     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_VCodecFramecopy,
763         mux_v->bih->biWidth, mux_v->bih->biHeight,
764         mux_v->bih->biBitCount, mux_v->bih->biCompression);
765
766         if (curfile) {
767                 if (sh_video->bih) {
768                         if ((mux_v->bih->biSize != sh_video->bih->biSize) ||
769                             memcmp(mux_v->bih, sh_video->bih, sh_video->bih->biSize))
770                         {
771                                 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_VCodecFramecopy,
772                                        sh_video->bih->biWidth, sh_video->bih->biHeight,
773                                        sh_video->bih->biBitCount, sh_video->bih->biCompression);
774                                 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_FrameCopyFileMismatch);
775                                 mencoder_exit(1,NULL);
776                         }
777                 }
778                 else {
779                         if ((mux_v->bih->biWidth != sh_video->disp_w) ||
780                             (mux_v->bih->biHeight != sh_video->disp_h) ||
781                             (mux_v->bih->biCompression != sh_video->format)) {
782                                 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_VCodecFramecopy,
783                                        sh_video->disp_w, sh_video->disp_w, 24, sh_video->format);
784                                 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_FrameCopyFileMismatch);
785                                 mencoder_exit(1,NULL);
786                         }
787                 }
788         }
789     break;
790 case VCODEC_FRAMENO:
791         if (!curfile) {
792     mux_v->bih=calloc(1,sizeof(BITMAPINFOHEADER));
793     mux_v->bih->biSize=sizeof(BITMAPINFOHEADER);
794     mux_v->bih->biWidth=sh_video->disp_w;
795     mux_v->bih->biHeight=sh_video->disp_h;
796     mux_v->bih->biPlanes=1;
797     mux_v->bih->biBitCount=24;
798     mux_v->bih->biCompression=mmioFOURCC('F','r','N','o');
799     mux_v->bih->biSizeImage=mux_v->bih->biWidth*mux_v->bih->biHeight*(mux_v->bih->biBitCount/8);
800         }
801     break;
802 default: {
803     static vf_instance_t * ve = NULL;
804   if (!ve) {
805     switch(mux_v->codec){
806     case VCODEC_LIBAVCODEC:
807         sh_video->vfilter=vf_open_encoder(NULL,"lavc",(char *)mux_v); break;
808     case VCODEC_RAW:
809         sh_video->vfilter=vf_open_encoder(NULL,"raw",(char *)mux_v); break;
810     case VCODEC_VFW:
811         sh_video->vfilter=vf_open_encoder(NULL,"vfw",(char *)mux_v); break;
812     case VCODEC_LIBDV:
813         sh_video->vfilter=vf_open_encoder(NULL,"libdv",(char *)mux_v); break;
814     case VCODEC_XVID:
815         sh_video->vfilter=vf_open_encoder(NULL,"xvid",(char *)mux_v); break;
816     case VCODEC_QTVIDEO:
817         sh_video->vfilter=vf_open_encoder(NULL,"qtvideo",(char *)mux_v); break;
818     case VCODEC_NUV:
819         sh_video->vfilter=vf_open_encoder(NULL,"nuv",(char *)mux_v); break;
820     case VCODEC_X264:
821         sh_video->vfilter=vf_open_encoder(NULL,"x264",(char *)mux_v); break;
822     }
823     if(!mux_v->bih || !sh_video->vfilter){
824         mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_EncoderOpenFailed);
825         mencoder_exit(1,NULL);
826     }
827     ve = sh_video->vfilter;
828   } else sh_video->vfilter = ve;
829     // append 'expand' filter, it fixes stride problems and renders osd:
830     if (auto_expand) {
831       char* vf_args[] = { "osd", "1", NULL };
832       sh_video->vfilter=vf_open_filter(sh_video->vfilter,"expand",vf_args);
833     }
834     sh_video->vfilter=append_filters(sh_video->vfilter);
835
836     mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
837     init_best_video_codec(sh_video,video_codec_list,video_fm_list);
838     mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
839     if(!sh_video->initialized) mencoder_exit(1,NULL);
840  }
841 }
842
843 if (!curfile) {
844 /* force output fourcc to .. */
845 if ((force_fourcc != NULL) && (strlen(force_fourcc) >= 4))
846 {
847     mux_v->bih->biCompression = mmioFOURCC(force_fourcc[0], force_fourcc[1],
848                                             force_fourcc[2], force_fourcc[3]);
849     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ForcingOutputFourcc,
850         mux_v->bih->biCompression, (char *)&mux_v->bih->biCompression);
851 }
852
853 if (! ignore_start)
854     muxer->audio_delay_fix -= sh_video->stream_delay;
855
856 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
857
858 // ============= AUDIO ===============
859 if(sh_audio){
860
861 if (force_audiofmttag != -1) {
862         sh_audio->format = force_audiofmttag;
863         if (sh_audio->wf) {
864                 sh_audio->wf->wFormatTag = sh_audio->format;
865         }
866         mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ForcingOutputAudiofmtTag,
867                force_audiofmttag);
868 }
869
870 mux_a=muxer_new_stream(muxer,MUXER_TYPE_AUDIO);
871
872 mux_a->buffer_size=0x100000; //16384;
873 mux_a->buffer=malloc(mux_a->buffer_size);
874 if (!mux_a->buffer)
875     mencoder_exit(1,MSGTR_MemAllocFailed);
876
877 mux_a->source=sh_audio;
878
879 mux_a->codec=out_audio_codec;
880
881 ao_data.samplerate = force_srate;
882 ao_data.channels = 0;
883 ao_data.format = audio_output_format;
884 if(!init_audio_filters(sh_audio,
885    // input:
886    new_srate,
887    // output:
888    &ao_data.samplerate, &ao_data.channels, &ao_data.format)) {
889      mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_AudioFilterChainPreinitError);
890      mencoder_exit(1, NULL);
891    }
892
893 aparams.channels = ao_data.channels;
894 aparams.sample_rate = ao_data.samplerate;
895 aparams.audio_preload = 1000 * audio_preload;
896 if(mux_a->codec != ACODEC_COPY) {
897     aencoder = new_audio_encoder(mux_a, &aparams);
898     if(!aencoder)
899         mencoder_exit(1, NULL);
900     if(!init_audio_filters(sh_audio,
901         new_srate,
902         &aparams.sample_rate, &aparams.channels, &aencoder->input_format)) {
903       mp_msg(MSGT_CPLAYER,MSGL_FATAL,MSGTR_NoMatchingFilter);
904       mencoder_exit(1,NULL);
905     }
906 }
907 switch(mux_a->codec){
908 case ACODEC_COPY:
909     if (playback_speed != 1.0) mp_msg(MSGT_CPLAYER, MSGL_WARN, MSGTR_NoSpeedWithFrameCopy);
910     if (sh_audio->format >= 0x10000) {
911         mp_msg(MSGT_MENCODER,MSGL_ERR,MSGTR_CantCopyAudioFormat, sh_audio->format);
912         mencoder_exit(1,NULL);
913     }
914     if (sh_audio->wf){
915         mux_a->wf=malloc(sizeof(WAVEFORMATEX) + sh_audio->wf->cbSize);
916         memcpy(mux_a->wf, sh_audio->wf, sizeof(WAVEFORMATEX) + sh_audio->wf->cbSize);
917         if(!sh_audio->i_bps) sh_audio->i_bps=mux_a->wf->nAvgBytesPerSec;
918     } else {
919         mux_a->wf = malloc(sizeof(WAVEFORMATEX));
920         mux_a->wf->nBlockAlign = 1; //mux_a->h.dwSampleSize;
921         mux_a->wf->wFormatTag = sh_audio->format;
922         mux_a->wf->nChannels = sh_audio->channels;
923         mux_a->wf->nSamplesPerSec = sh_audio->samplerate;
924         mux_a->wf->nAvgBytesPerSec=sh_audio->i_bps; //mux_a->h.dwSampleSize*mux_a->wf->nSamplesPerSec;
925         mux_a->wf->wBitsPerSample = 16; // FIXME
926         mux_a->wf->cbSize=0; // FIXME for l3codeca.acm
927     }
928     if(sh_audio->audio.dwScale){
929         mux_a->h.dwSampleSize=sh_audio->audio.dwSampleSize;
930         mux_a->h.dwScale=sh_audio->audio.dwScale;
931         mux_a->h.dwRate=sh_audio->audio.dwRate;
932     } else {
933         mux_a->h.dwSampleSize=mux_a->wf->nBlockAlign;
934         mux_a->h.dwScale=mux_a->h.dwSampleSize;
935         mux_a->h.dwRate=mux_a->wf->nAvgBytesPerSec;
936     }
937     mux_a->h.dwRate *= playback_speed;
938     mux_a->wf->nSamplesPerSec *= playback_speed;
939     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ACodecFramecopy,
940         mux_a->wf->wFormatTag, mux_a->wf->nChannels, mux_a->wf->nSamplesPerSec,
941         mux_a->wf->wBitsPerSample, mux_a->wf->nAvgBytesPerSec, mux_a->h.dwSampleSize);
942     break;
943 }
944
945 if ( mp_msg_test(MSGT_MENCODER,MSGL_DBG2) ) print_wave_header(mux_a->wf, MSGL_DBG2);
946
947 if (! ignore_start)
948     muxer->audio_delay_fix += sh_audio->stream_delay;
949
950 } // if(sh_audio)
951
952 decoded_frameno=0;
953
954 signal(SIGINT,exit_sighandler);  // Interrupt from keyboard
955 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
956 signal(SIGTERM,exit_sighandler); // kill
957 signal(SIGHUP,exit_sighandler);  // broken terminal line
958 signal(SIGPIPE,exit_sighandler); // broken pipe
959
960 timer_start=GetTimerMS();
961 } // if (!curfile) // if this was the first file.
962 else {
963         if (!mux_a != !sh_audio) {
964                 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_NoAudioFileMismatch);
965                 mencoder_exit(1,NULL);
966         }
967         if (sh_audio && mux_a->codec == ACODEC_COPY) {
968                 if (playback_speed != 1.0) mp_msg(MSGT_CPLAYER, MSGL_WARN, MSGTR_NoSpeedWithFrameCopy);
969                 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ACodecFramecopy,
970                        mux_a->wf->wFormatTag, mux_a->wf->nChannels, mux_a->wf->nSamplesPerSec,
971                        mux_a->wf->wBitsPerSample, mux_a->wf->nAvgBytesPerSec, mux_a->h.dwSampleSize);
972                 if (sh_audio->wf) {
973                         if ((mux_a->wf->wFormatTag != sh_audio->wf->wFormatTag) ||
974                             (mux_a->wf->nChannels != sh_audio->wf->nChannels) ||
975                             (mux_a->wf->nSamplesPerSec != sh_audio->wf->nSamplesPerSec * playback_speed))
976                         {
977                                 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ACodecFramecopy,
978                                        sh_audio->wf->wFormatTag, sh_audio->wf->nChannels, (int)(sh_audio->wf->nSamplesPerSec * playback_speed),
979                                        sh_audio->wf->wBitsPerSample, sh_audio->wf->nAvgBytesPerSec, 0);
980                                 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_AudioCopyFileMismatch);
981                                 mencoder_exit(1,NULL);
982                         }
983                 } else {
984                         if ((mux_a->wf->wFormatTag != sh_audio->format) ||
985                             (mux_a->wf->nChannels != sh_audio->channels) ||
986                             (mux_a->wf->nSamplesPerSec != sh_audio->samplerate * playback_speed))
987                         {
988                                 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_ACodecFramecopy,
989                                        sh_audio->wf->wFormatTag, sh_audio->wf->nChannels, (int)(sh_audio->wf->nSamplesPerSec * playback_speed),
990                                        sh_audio->wf->wBitsPerSample, sh_audio->wf->nAvgBytesPerSec, 0);
991                                 mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_AudioCopyFileMismatch);
992                                 mencoder_exit(1,NULL);
993                         }
994                 }
995         } else if (sh_audio) {
996                 int out_srate = mux_a->wf->nSamplesPerSec;
997                 int out_channels = mux_a->wf->nChannels;
998                 int out_format = aencoder->input_format;
999                 if (!init_audio_filters(sh_audio, new_srate,
1000                                         &out_srate, &out_channels,
1001                                         &out_format)) {
1002                         mp_msg(MSGT_CPLAYER, MSGL_FATAL, MSGTR_NoMatchingFilter);
1003                         mencoder_exit(1, NULL);
1004                 }
1005                 mux_a->wf->nSamplesPerSec = out_srate;
1006                 mux_a->wf->nChannels = out_channels;
1007         }
1008 }
1009
1010 if (seek_to_sec) {
1011     demux_seek(demuxer, seek_to_sec, audio_delay, 1);
1012 //  there is 2 way to handle the -ss option in 3-pass mode:
1013 // > 1. do the first pass for the whole file, and use -ss for 2nd/3rd pases only
1014 // > 2. do all the 3 passes with the same -ss value
1015 //  this line enables behaviour 1. (and kills 2. at the same time):
1016 //    if(demuxer2) demux_seek(demuxer2, d, audio_delay, 1);
1017 }
1018
1019 if (out_file_format == MUXER_TYPE_MPEG)
1020         {
1021         if (audio_preload > 0.4) {
1022           mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_LimitingAudioPreload);
1023           audio_preload = 0.4;
1024         }
1025         if (audio_density < 4) {
1026           mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_IncreasingAudioDensity);
1027           audio_density = 4;
1028         }
1029         }
1030
1031 if(file_format == DEMUXER_TYPE_TV)
1032         {
1033         mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_ZeroingAudioPreloadAndMaxPtsCorrection);
1034         audio_preload = 0.0;
1035         default_max_pts_correction = 0;
1036         }
1037
1038 play_n_frames=play_n_frames_mf;
1039 if (curfile && end_at.type == END_AT_TIME) end_at.pos += mux_v->timer;
1040
1041 if (edl_records) free_edl(edl_records);
1042 next_edl_record = edl_records = NULL;
1043 edl_muted = 0;
1044 edl_seeking = 1;
1045 if (edl_filename) {
1046     next_edl_record = edl_records = edl_parse_file();
1047 }
1048
1049 if (sh_audio && audio_delay != 0.) fixdelay(d_video, d_audio, mux_a, &frame_data, mux_v->codec==VCODEC_COPY);
1050
1051 while(!at_eof){
1052
1053     int blit_frame=0;
1054     float a_pts=0;
1055     float v_pts=0;
1056     int skip_flag=0; // 1=skip  -1=duplicate
1057
1058     if((end_at.type == END_AT_SIZE && end_at.pos <= stream_tell(muxer->stream))  ||
1059        (end_at.type == END_AT_TIME && end_at.pos < mux_v->timer))
1060         break;
1061
1062     if(play_n_frames>=0){
1063       --play_n_frames;
1064       if(play_n_frames<0) break;
1065     }
1066     if(dvd_last_chapter>0) {
1067       int cur_chapter = demuxer_get_current_chapter(demuxer);
1068       if(cur_chapter!=-1 && cur_chapter+1>dvd_last_chapter)
1069         break;
1070     }
1071
1072 goto_redo_edl:
1073     if (next_edl_record && sh_video && sh_video->pts >= next_edl_record->start_sec) {
1074         if (next_edl_record->action == EDL_SKIP && edl_seeking) {
1075             float last_pos = d_video->pts;
1076             int result;
1077             mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop [%f], length [%f]\n",
1078                    next_edl_record->start_sec, next_edl_record->stop_sec, next_edl_record->length_sec);
1079
1080             result = edl_seek(next_edl_record, demuxer, d_audio, mux_a, &frame_data, mux_v->codec==VCODEC_COPY);
1081
1082             if (result == 2) { at_eof=1; break; } // EOF
1083             else if (result == 0) edl_seeking = 0; // no seeking
1084             else { // sucess
1085                 edl_muted = 0;
1086                 if (last_pos >= sh_video->pts) {
1087                     // backwards seek detected!! Forget about this EDL skip altogether.
1088                     next_edl_record = next_edl_record->next;
1089                 }
1090                 else for (next_edl_record = edl_records; next_edl_record; next_edl_record = next_edl_record->next) {
1091                     /* note the use of stop_sec,
1092                        meaning if by some magical way we landed in the MIDDLE of a censored area,
1093                        in the next loop it will jump out of it.
1094                     */
1095                     if (next_edl_record->stop_sec > sh_video->pts) break; // we got to the right place.
1096                     if (next_edl_record->action == EDL_MUTE) edl_muted = !edl_muted; // toggle mute each time.
1097                 }
1098
1099                 /* for a pedantic EDL, that doesn't show even a single
1100                    frame from the "censored" area, uncomment next line. */
1101                 goto goto_redo_edl;
1102             }
1103         } else if (next_edl_record->action == EDL_MUTE) {
1104             edl_muted = !edl_muted;  // This variable does nothing for now.
1105             mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n", next_edl_record->start_sec );
1106             next_edl_record=next_edl_record->next;
1107         }
1108     }
1109
1110
1111 if(sh_audio){
1112     // get audio:
1113     while(mux_a->timer-audio_preload<mux_v->timer){
1114         float tottime;
1115         int len=0;
1116
1117         ptimer_start = GetTimerMS();
1118         // CBR - copy 0.5 sec of audio
1119         // or until the end of video:
1120         tottime = stop_time(demuxer, mux_v);
1121         if (tottime != -1) {
1122                 tottime -= mux_a->timer;
1123                 if (tottime > 1./audio_density) tottime = 1./audio_density;
1124         }
1125         else tottime = 1./audio_density;
1126
1127         // let's not output more audio than necessary
1128         if (tottime <= 0) break;
1129
1130         if(aencoder)
1131         {
1132                 if(mux_a->h.dwSampleSize) /* CBR */
1133                 {
1134                         if(aencoder->set_decoded_len)
1135                         {
1136                                 len = mux_a->h.dwSampleSize*(int)(mux_a->h.dwRate*tottime);
1137                                 aencoder->set_decoded_len(aencoder, len);
1138                         }
1139                         else
1140                                 len = aencoder->decode_buffer_size;
1141
1142                         len = dec_audio(sh_audio, aencoder->decode_buffer, len);
1143                         mux_a->buffer_len += aencoder->encode(aencoder, mux_a->buffer + mux_a->buffer_len,
1144                                 aencoder->decode_buffer, len, mux_a->buffer_size-mux_a->buffer_len);
1145                         if(mux_a->buffer_len < mux_a->wf->nBlockAlign)
1146                                 len = 0;
1147                         else
1148                                 len = mux_a->wf->nBlockAlign*(mux_a->buffer_len/mux_a->wf->nBlockAlign);
1149                 }
1150                 else    /* VBR */
1151                 {
1152                         int sz = 0;
1153                         while(1)
1154                         {
1155                                 len = 0;
1156                                 if(! sz)
1157                                         sz = aencoder->get_frame_size(aencoder);
1158                                 if(sz > 0 && mux_a->buffer_len >= sz)
1159                                 {
1160                                         len = sz;
1161                                         break;
1162                                 }
1163                                 len = dec_audio(sh_audio,aencoder->decode_buffer, aencoder->decode_buffer_size);
1164                                 if(len <= 0)
1165                                 {
1166                                         len = 0;
1167                                         break;
1168                                 }
1169                                 len = aencoder->encode(aencoder, mux_a->buffer + mux_a->buffer_len, aencoder->decode_buffer, len, mux_a->buffer_size-mux_a->buffer_len);
1170                                 mux_a->buffer_len += len;
1171                         }
1172             }
1173             if (mux_v->timer == 0) mux_a->h.dwInitialFrames++;
1174         }
1175         else {
1176         if(mux_a->h.dwSampleSize){
1177             switch(mux_a->codec){
1178             case ACODEC_COPY: // copy
1179                 len=mux_a->wf->nAvgBytesPerSec*tottime;
1180                 len/=mux_a->h.dwSampleSize;if(len<1) len=1;
1181                 len*=mux_a->h.dwSampleSize;
1182                 len=demux_read_data(sh_audio->ds,mux_a->buffer,len);
1183                 break;
1184             }
1185         } else {
1186             // VBR - encode/copy an audio frame
1187             switch(mux_a->codec){
1188             case ACODEC_COPY: // copy
1189                 len=ds_get_packet(sh_audio->ds,(unsigned char**) &mux_a->buffer);
1190                 break;
1191                 }
1192             }
1193         }
1194         if(len<=0) break; // EOF?
1195         muxer_write_chunk(mux_a,len,0x10, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1196         if(!mux_a->h.dwSampleSize && mux_a->timer>0)
1197             mux_a->wf->nAvgBytesPerSec=0.5f+(double)mux_a->size/mux_a->timer; // avg bps (VBR)
1198         if(mux_a->buffer_len>=len){
1199             mux_a->buffer_len-=len;
1200             fast_memcpy(mux_a->buffer,mux_a->buffer+len,mux_a->buffer_len);
1201         }
1202
1203
1204         audiosamples++;
1205         audiorate+= (GetTimerMS() - ptimer_start);
1206
1207     }
1208 }
1209
1210     // get video frame!
1211
1212     if (!frame_data.already_read) {
1213         frame_data.in_size=video_read_frame(sh_video,&frame_data.frame_time,&frame_data.start,force_fps);
1214         sh_video->timer+=frame_data.frame_time;
1215     }
1216     frame_data.frame_time /= playback_speed;
1217     if(frame_data.in_size<0){ at_eof=1; break; }
1218     ++decoded_frameno;
1219
1220     v_timer_corr-=frame_data.frame_time-(float)mux_v->h.dwScale/mux_v->h.dwRate;
1221
1222 if(demuxer2){   // 3-pass encoding, read control file (frameno.avi)
1223     // find our frame:
1224         while(next_frameno<decoded_frameno){
1225             int* start;
1226             int len=ds_get_packet(demuxer2->video,(unsigned char**) &start);
1227             if(len<0){ at_eof=1;break;}
1228             if(len==0) --skip_flag; else  // duplicate
1229             if(len==4) next_frameno=start[0];
1230         }
1231     if(at_eof) break;
1232         // if(skip_flag) printf("!!!!!!!!!!!!\n");
1233         skip_flag=next_frameno-decoded_frameno;
1234     // find next frame:
1235         while(next_frameno<=decoded_frameno){
1236             int* start;
1237             int len=ds_get_packet(demuxer2->video,(unsigned char**) &start);
1238             if(len<0){ at_eof=1;break;}
1239             if(len==0) --skip_flag; else  // duplicate
1240             if(len==4) next_frameno=start[0];
1241         }
1242 //    if(at_eof) break;
1243 //          printf("Current fno=%d  requested=%d  skip=%d  \n",decoded_frameno,fno,skip_flag);
1244 } else {
1245
1246 // check frame duplicate/drop:
1247
1248 //printf("\r### %5.3f ###\n",v_timer_corr);
1249 float mux_frametime = (float)mux_v->h.dwScale/mux_v->h.dwRate;
1250
1251 if (v_timer_corr >= mux_frametime && (skip_limit<0 || skip_flag < skip_limit)) {
1252     v_timer_corr-=mux_frametime;
1253     ++skip_flag; // skip
1254 }
1255 while (v_timer_corr <= -mux_frametime && (skip_limit<0 || -skip_flag < skip_limit)) {
1256     v_timer_corr+=mux_frametime;
1257     --skip_flag; // dup
1258 }
1259
1260 // either v_pts_corr is big, more than 2 times framerate, then we follow its advice,
1261 // or, it cancels out v_timer_corr, in which case be happy and do nothing.
1262
1263 while ((v_pts_corr <= -mux_frametime && skip_flag > 0) || (v_pts_corr <= -2*mux_frametime)) {
1264     v_pts_corr+=mux_frametime;
1265     --skip_flag; // dup
1266 }
1267 if ((v_pts_corr >= mux_frametime && skip_flag < 0) || (v_pts_corr >= 2*mux_frametime)) {
1268   if (skip_flag<=0) { // we can't skip more than 1 frame now
1269     v_pts_corr-=mux_frametime;
1270     ++skip_flag; // skip
1271   }
1272 }
1273
1274 } // demuxer2
1275
1276 ptimer_start = GetTimerMS();
1277
1278 switch(mux_v->codec){
1279 case VCODEC_COPY:
1280     mux_v->buffer=frame_data.start;
1281     if(skip_flag<=0) muxer_write_chunk(mux_v,frame_data.in_size,(sh_video->ds->flags&1)?0x10:0, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1282     break;
1283 case VCODEC_FRAMENO:
1284     mux_v->buffer=(unsigned char *)&decoded_frameno; // tricky
1285     if(skip_flag<=0) muxer_write_chunk(mux_v,sizeof(int),0x10, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1286     break;
1287 default:
1288     // decode_video will callback down to ve_*.c encoders, through the video filters
1289     {void *decoded_frame = decode_video(sh_video,frame_data.start,frame_data.in_size,
1290       skip_flag>0 && (!sh_video->vfilter || ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter, VFCTRL_SKIP_NEXT_FRAME, 0) != CONTROL_TRUE), MP_NOPTS_VALUE);
1291     blit_frame = decoded_frame && filter_video(sh_video, decoded_frame, MP_NOPTS_VALUE);}
1292
1293     if (sh_video->vf_initialized < 0) mencoder_exit(1, NULL);
1294
1295     if(!blit_frame){
1296       if (play_n_frames >= 0)
1297         play_n_frames++;
1298       badframes++;
1299       if(skip_flag<=0){
1300         // unwanted skipping of a frame, what to do?
1301         v_timer_corr-=(float)mux_v->h.dwScale/mux_v->h.dwRate;
1302 #if 0
1303         // Old code apparently made under the assumption that !blit_frame means
1304         // decoding failed due to corruption or something.. but duplication and
1305         // skipping of frames should be entirely disabled when skip_limit==0,
1306         // and must be in order for many filters to work with -noskip.
1307         // Eventually this entire block should probably be removed.
1308         if(skip_limit==0){
1309             // skipping not allowed -> write empty frame:
1310             if (!encode_duplicates || !sh_video->vfilter || ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter, VFCTRL_DUPLICATE_FRAME, 0) != CONTROL_TRUE)
1311               muxer_write_chunk(mux_v,0,0, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1312         } else {
1313             // skipping allowed -> skip it and distriubute timer error:
1314             v_timer_corr-=(float)mux_v->h.dwScale/mux_v->h.dwRate;
1315         }
1316 #endif
1317       }
1318     }
1319 }
1320
1321 videosamples++;
1322 videorate+=(GetTimerMS() - ptimer_start);
1323
1324 if(skip_flag<0){
1325     // duplicate frame
1326         if(!quiet) mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_DuplicateFrames,-skip_flag);
1327     while(skip_flag<0){
1328         duplicatedframes++;
1329         if (!encode_duplicates || !sh_video->vfilter || ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter, VFCTRL_DUPLICATE_FRAME, 0) != CONTROL_TRUE)
1330             muxer_write_chunk(mux_v,0,0, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1331         ++skip_flag;
1332     }
1333 } else
1334 if(skip_flag>0){
1335     // skip frame
1336         if(!quiet) mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_SkipFrame);
1337         skippedframes++;
1338     --skip_flag;
1339 }
1340
1341 if(sh_audio && !demuxer2){
1342     float AV_delay,x;
1343     // A-V sync!
1344 #if 0
1345     if(pts_from_bps){
1346         unsigned int samples=(sh_audio->audio.dwSampleSize)?
1347           ((ds_tell(d_audio)-sh_audio->a_in_buffer_len)/sh_audio->audio.dwSampleSize) :
1348           (d_audio->block_no); // <- used for VBR audio
1349 //      printf("samples=%d  \n",samples);
1350         a_pts=samples*(float)sh_audio->audio.dwScale/(float)sh_audio->audio.dwRate;
1351       delay_corrected=1;
1352     } else
1353 #endif
1354     {
1355       // PTS = (last timestamp) + (bytes after last timestamp)/(bytes per sec)
1356       a_pts=d_audio->pts;
1357       if(!delay_corrected) if(a_pts) delay_corrected=1;
1358       //printf("*** %5.3f ***\n",a_pts);
1359       a_pts+=(ds_tell_pts(d_audio)-sh_audio->a_in_buffer_len)/(float)sh_audio->i_bps;
1360     }
1361     v_pts=sh_video ? sh_video->pts : d_video->pts;
1362     // av = compensated (with out buffering delay) A-V diff
1363     AV_delay=(a_pts-v_pts);
1364     AV_delay-=audio_delay;
1365     AV_delay /= playback_speed;
1366     AV_delay-=mux_a->timer-(mux_v->timer-(v_timer_corr+v_pts_corr));
1367     // adjust for encoder delays
1368     AV_delay -= (float) mux_a->encoder_delay * mux_a->h.dwScale/mux_a->h.dwRate;
1369     AV_delay += (float) mux_v->encoder_delay * mux_v->h.dwScale/mux_v->h.dwRate;
1370         // compensate input video timer by av:
1371         x=AV_delay*0.1f;
1372         if(x<-max_pts_correction) x=-max_pts_correction; else
1373         if(x> max_pts_correction) x= max_pts_correction;
1374         if(default_max_pts_correction>=0)
1375           max_pts_correction=default_max_pts_correction*playback_speed;
1376         else
1377           max_pts_correction=sh_video->frametime*0.10 *playback_speed; // +-10% of time
1378         // sh_video->timer-=x;
1379         c_total+=x;
1380         v_pts_corr+=x;
1381 }
1382
1383 //    printf("A:%6.1f V:%6.1f A-V:%7.3f oAV:%7.3f diff:%7.3f ct:%7.3f vpc:%7.3f   \r",
1384 //      a_pts,v_pts,a_pts-v_pts,
1385 //      (float)(mux_a->timer-mux_v->timer),
1386 //      AV_delay, c_total, v_pts_corr );
1387 //    printf("V:%6.1f \r", d_video->pts );
1388
1389 #if 0
1390     mp_msg(MSGT_AVSYNC,MSGL_STATUS,"A:%6.1f V:%6.1f A-V:%7.3f ct:%7.3f  %3d/%3d  %2d%% %2d%% %4.1f%%  %d%%\r",
1391           a_pts,v_pts,a_pts-v_pts,c_total,
1392           (int)sh_video->num_frames,(int)sh_video->num_frames_decoded,
1393           (sh_video->timer>0.5)?(int)(100.0*video_time_usage/(double)sh_video->timer):0,
1394           (sh_video->timer>0.5)?(int)(100.0*vout_time_usage/(double)sh_video->timer):0,
1395           (sh_video->timer>0.5)?(100.0*audio_time_usage/(double)sh_video->timer):0
1396           ,cache_fill_status
1397         );
1398 #endif
1399
1400     {   float t=(GetTimerMS()-timer_start)*0.001f;
1401         float len=(demuxer->movi_end-demuxer->movi_start);
1402         float p=len>1000 ? (float)(demuxer->filepos-demuxer->movi_start) / len :
1403                 (demuxer_get_percent_pos(demuxer) / 100.0);
1404 #if 0
1405         if(!len && sh_audio && sh_audio->audio.dwLength>100){
1406             p=(sh_audio->audio.dwSampleSize? ds_tell(sh_audio->ds)/sh_audio->audio.dwSampleSize : sh_audio->ds->block_no)
1407              / (float)(sh_audio->audio.dwLength);
1408         }
1409 #endif
1410 #if 0
1411         mp_msg(MSGT_AVSYNC,MSGL_STATUS,"%d < %d < %d  \r",
1412             (int)demuxer->movi_start,
1413             (int)demuxer->filepos,
1414             (int)demuxer->movi_end);
1415 #else
1416       if(!quiet) {
1417         if( mp_msg_test(MSGT_STATUSLINE,MSGL_V) ) {
1418                 mp_msg(MSGT_STATUSLINE,MSGL_STATUS,"Pos:%6.1fs %6df (%2d%%) %3dfps Trem:%4dmin %3dmb  A-V:%5.3f [%d:%d] A/Vms %d/%d D/B/S %d/%d/%d \r",
1419                 mux_v->timer, decoded_frameno, (int)(p*100),
1420                 (t>1) ? (int)(decoded_frameno/t+0.5) : 0,
1421                 (p>0.001) ? (int)((t/p-t)/60) : 0,
1422                 (p>0.001) ? (int)(stream_tell(muxer->stream)/p/1024/1024) : 0,
1423                 v_pts_corr,
1424                 (mux_v->timer>1) ? (int)(mux_v->size/mux_v->timer/125) : 0,
1425                 (mux_a && mux_a->timer>1) ? (int)(mux_a->size/mux_a->timer/125) : 0,
1426                         audiorate/audiosamples, videorate/videosamples,
1427                         duplicatedframes, badframes, skippedframes
1428                 );
1429         } else
1430         mp_msg(MSGT_STATUSLINE,MSGL_STATUS,"Pos:%6.1fs %6df (%2d%%) %5.2ffps Trem:%4dmin %3dmb  A-V:%5.3f [%d:%d]\r",
1431             mux_v->timer, decoded_frameno, (int)(p*100),
1432             (t>1) ? (float)(decoded_frameno/t) : 0,
1433             (p>0.001) ? (int)((t/p-t)/60) : 0,
1434             (p>0.001) ? (int)(stream_tell(muxer->stream)/p/1024/1024) : 0,
1435             v_pts_corr,
1436             (mux_v->timer>1) ? (int)(mux_v->size/mux_v->timer/125) : 0,
1437             (mux_a && mux_a->timer>1) ? (int)(mux_a->size/mux_a->timer/125) : 0
1438         );
1439       }
1440 #endif
1441     }
1442         fflush(stdout);
1443
1444 #ifdef CONFIG_DVDREAD
1445 // DVD sub:
1446  if(vobsub_writer){
1447      unsigned char* packet=NULL;
1448      int len;
1449      while((len=ds_get_packet_sub(d_dvdsub,&packet))>0){
1450          mp_msg(MSGT_MENCODER,MSGL_V,"\rDVD sub: len=%d  v_pts=%5.3f  s_pts=%5.3f  \n",len,sh_video->pts,d_dvdsub->pts);
1451              vobsub_out_output(vobsub_writer,packet,len,mux_v->timer + d_dvdsub->pts - sh_video->pts);
1452      }
1453  }
1454  else
1455 #endif
1456     update_subtitles(sh_video, d_dvdsub, 0);
1457
1458  frame_data = (s_frame_data){ .start = NULL, .in_size = 0, .frame_time = 0., .already_read = 0 };
1459
1460 #if 0
1461  if(ferror(muxer_f)) {
1462      mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_ErrorWritingFile, out_filename);
1463      mencoder_exit(1, NULL);
1464  }
1465 #endif
1466
1467 } // while(!at_eof)
1468
1469 if (!interrupted && filelist[++curfile].name != 0) {
1470         if (sh_video && sh_video->vfilter) { // Before uniniting sh_video and the filter chain, break apart the VE.
1471                 vf_instance_t * ve; // this will be the filter right before the ve.
1472                 for (ve = sh_video->vfilter; ve->next && ve->next->next; ve = ve->next);
1473
1474                 if (ve->next) ve->next = NULL; // I'm telling the last filter, before the VE, there is nothing after it
1475                 else sh_video->vfilter = NULL; // There is no chain except the VE.
1476         }
1477
1478         if(sh_audio){ uninit_audio(sh_audio);sh_audio=NULL; }
1479         if(sh_video){ uninit_video(sh_video);sh_video=NULL; }
1480         if(demuxer) free_demuxer(demuxer);
1481         if(stream) free_stream(stream); // kill cache thread
1482
1483         at_eof = 0;
1484
1485         m_config_pop(mconfig);
1486         goto play_next_file;
1487 }
1488
1489 /* Emit the remaining frames in the video system */
1490 /*TODO emit frmaes delayed by decoder lag*/
1491 if(sh_video && sh_video->vfilter){
1492         mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_FlushingVideoFrames);
1493         if (!((vf_instance_t *)sh_video->vfilter)->fmt.have_configured)
1494                 mp_msg(MSGT_MENCODER, MSGL_WARN, MSGTR_FiltersHaveNotBeenConfiguredEmptyFile);
1495         else
1496                 ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter,
1497                                                       VFCTRL_FLUSH_FRAMES, 0);
1498 }
1499
1500 if(aencoder)
1501     if(aencoder->fixup)
1502         aencoder->fixup(aencoder);
1503
1504 if (muxer->cont_write_index) muxer_write_index(muxer);
1505 muxer_f_size=stream_tell(muxer->stream);
1506 stream_seek(muxer->stream,0);
1507 if (muxer->cont_write_header) muxer_write_header(muxer); // update header
1508 #if 0
1509 if(ferror(muxer_f) || fclose(muxer_f) != 0) {
1510     mp_msg(MSGT_MENCODER,MSGL_FATAL,MSGTR_ErrorWritingFile, out_filename);
1511     mencoder_exit(1, NULL);
1512 }
1513 #endif
1514 if(vobsub_writer)
1515     vobsub_out_close(vobsub_writer);
1516
1517 if(out_video_codec==VCODEC_FRAMENO && mux_v->timer>100){
1518     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"650MB",(int)((650*1024*1024-muxer_f_size)/mux_v->timer/125));
1519     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"700MB",(int)((700*1024*1024-muxer_f_size)/mux_v->timer/125));
1520     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"800MB",(int)((800*1024*1024-muxer_f_size)/mux_v->timer/125));
1521     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"2 x 650MB",(int)((2*650*1024*1024-muxer_f_size)/mux_v->timer/125));
1522     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"2 x 700MB",(int)((2*700*1024*1024-muxer_f_size)/mux_v->timer/125));
1523     mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_RecommendedVideoBitrate,"2 x 800MB",(int)((2*800*1024*1024-muxer_f_size)/mux_v->timer/125));
1524 }
1525
1526 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_VideoStreamResult,
1527     (float)(mux_v->size/mux_v->timer*8.0f/1000.0f), (int)(mux_v->size/mux_v->timer), (uint64_t)mux_v->size, (float)mux_v->timer, decoded_frameno);
1528 if(sh_audio)
1529 mp_msg(MSGT_MENCODER, MSGL_INFO, MSGTR_AudioStreamResult,
1530     (float)(mux_a->size/mux_a->timer*8.0f/1000.0f), (int)(mux_a->size/mux_a->timer), (uint64_t)mux_a->size, (float)mux_a->timer);
1531
1532 if(sh_audio){ uninit_audio(sh_audio);sh_audio=NULL; }
1533 if(sh_video){ uninit_video(sh_video);sh_video=NULL; }
1534 if(demuxer) free_demuxer(demuxer);
1535 if(stream) free_stream(stream); // kill cache thread
1536
1537 return interrupted;
1538 }
1539
1540
1541 #if 0
1542 /* Flip the image in src and store the result in dst. src and dst may overlap.
1543    width is the size of each line in bytes. */
1544 static uint8_t* flip_upside_down(uint8_t* dst, const uint8_t* src, int width,
1545                                  int height)
1546 {
1547     uint8_t* tmp = malloc(width);
1548     int i;
1549
1550     for(i = 0; i < height/2; i++) {
1551         fast_memcpy(tmp, &src[i*width], width);
1552         fast_memcpy(&dst[i * width], &src[(height - i) * width], width);
1553         fast_memcpy(&dst[(height - i) * width], tmp, width);
1554     }
1555
1556     free(tmp);
1557     return dst;
1558 }
1559 #endif
1560
1561
1562 static float stop_time(demuxer_t* demuxer, muxer_stream_t* mux_v) {
1563         float timeleft = -1;
1564         if (play_n_frames >= 0) timeleft = mux_v->timer + play_n_frames * (double)(mux_v->h.dwScale) / mux_v->h.dwRate;
1565         if (end_at.type == END_AT_TIME && (timeleft > end_at.pos || timeleft == -1)) timeleft = end_at.pos;
1566         if (next_edl_record && demuxer && demuxer->video) { // everything is OK to be checked
1567                 float tmp = mux_v->timer + next_edl_record->start_sec - demuxer->video->pts;
1568                 if (timeleft == -1 || timeleft > tmp) {
1569                         // There's less time in EDL than what we already know
1570                         if (next_edl_record->action == EDL_SKIP && edl_seeking) {
1571                                 timeleft = tmp;
1572                         } else if (next_edl_record->action == EDL_MUTE) {
1573                                 //timeleft = next_edl_record->start_sec - demuxer->video->pts;
1574                                 // For the moment (and probably forever) EDL mute doesn't work in MEncoder
1575                         }
1576                 }
1577         }
1578         return timeleft;
1579 }
1580
1581 static float calc_a_pts(demux_stream_t *d_audio) {
1582     sh_audio_t * sh_audio = d_audio ? d_audio->sh : NULL;
1583     float a_pts = 0.;
1584     if (sh_audio)
1585         a_pts = d_audio->pts + (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len)/(float)sh_audio->i_bps;
1586     return a_pts;
1587 }
1588
1589 static float forward_audio(float pts, demux_stream_t *d_audio, muxer_stream_t* mux_a) {
1590     sh_audio_t * sh_audio = d_audio ? d_audio->sh : NULL;
1591     int samplesize, avg;
1592     float a_pts = calc_a_pts(d_audio);
1593
1594     if (!sh_audio) return a_pts;
1595
1596     if (sh_audio->audio.dwScale) samplesize = sh_audio->audio.dwSampleSize;
1597     else samplesize = (sh_audio->wf ? sh_audio->wf->nBlockAlign : 1);
1598     avg = (sh_audio->wf ? sh_audio->wf->nAvgBytesPerSec : sh_audio->i_bps);
1599
1600     // after a demux_seek, a_pts will be zero until you read some audio.
1601     // carefully checking if a_pts is truely correct by reading tiniest amount of data possible.
1602     if (pts > a_pts && a_pts == 0.0 && samplesize) {
1603         if (demux_read_data(sh_audio->ds,mux_a->buffer,samplesize) <= 0) return a_pts; // EOF
1604         a_pts = calc_a_pts(d_audio);
1605     }
1606
1607     while (pts > a_pts) {
1608         int len;
1609         if (samplesize) {
1610             len = avg * (pts - a_pts > 0.5 ? 0.5 : pts - a_pts);
1611             len/= samplesize; if(len<1) len=1;
1612             len*= samplesize;
1613             len = demux_read_data(sh_audio->ds,mux_a->buffer,len);
1614         } else {
1615             unsigned char * crap;
1616             len = ds_get_packet(sh_audio->ds, &crap);
1617         }
1618         if (len <= 0) break; // EOF of audio.
1619         a_pts = calc_a_pts(d_audio);
1620     }
1621     return a_pts;
1622 }
1623
1624 static int slowseek(float end_pts, demux_stream_t *d_video, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy, int print_info) {
1625     sh_video_t * sh_video = d_video->sh;
1626     vf_instance_t * vfilter = sh_video ? sh_video->vfilter : NULL;
1627     int done = 0;
1628
1629     while (!interrupted) {
1630         float a_pts = 0.;
1631
1632         if (!frame_data->already_read) { // when called after fixdelay, a frame is already read
1633             frame_data->in_size = video_read_frame(sh_video, &frame_data->frame_time, &frame_data->start, force_fps);
1634             if(frame_data->in_size<0) return 2;
1635             sh_video->timer += frame_data->frame_time;
1636         }
1637         frame_data->already_read = 0;
1638
1639         a_pts = forward_audio(sh_video->pts - frame_data->frame_time + audio_delay, d_audio, mux_a);
1640
1641         if (done) {
1642             // wait for keyframe in case of -ovc copy
1643             if (!framecopy || (sh_video->ds->flags & 1)) {
1644                 frame_data->already_read = 1;
1645                 return 1;
1646             }
1647         }
1648         if (sh_video->pts >= end_pts) done = 1;
1649
1650         if (vfilter) {
1651             int softskip = (vfilter->control(vfilter, VFCTRL_SKIP_NEXT_FRAME, 0) == CONTROL_TRUE);
1652             void *decoded_frame = decode_video(sh_video, frame_data->start, frame_data->in_size, !softskip, MP_NOPTS_VALUE);
1653             if (decoded_frame)
1654                 filter_video(sh_video, decoded_frame, MP_NOPTS_VALUE);
1655         }
1656
1657         if (print_info) mp_msg(MSGT_MENCODER, MSGL_STATUS,
1658                MSGTR_EdlSkipStartEndCurrent,
1659                next_edl_record->start_sec, next_edl_record->stop_sec,
1660                sh_video->pts, a_pts);
1661     }
1662     if (interrupted) return 2;
1663     return 1;
1664 }
1665
1666 static void fixdelay(demux_stream_t *d_video, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy) {
1667     // TODO: Find a way to encode silence instead of deleting video
1668     sh_video_t * sh_video = d_video->sh;
1669     float a_pts;
1670
1671     // demux_seek has a weirdness that sh_video->pts is meaningless,
1672     // until a single frame is read... Same for audio actually too.
1673     // Reading one frame, and keeping it.
1674     frame_data->in_size = video_read_frame(sh_video, &frame_data->frame_time, &frame_data->start, force_fps);
1675     if(frame_data->in_size<0) return;
1676     sh_video->timer += frame_data->frame_time;
1677     frame_data->already_read = 1;
1678
1679     a_pts = forward_audio(sh_video->pts - frame_data->frame_time + audio_delay, d_audio, mux_a);
1680
1681     if (audio_delay > 0) return;
1682     else if (sh_video->pts - frame_data->frame_time + audio_delay >= a_pts) return;
1683
1684     slowseek(a_pts - audio_delay, d_video, d_audio, mux_a, frame_data, framecopy, 0);
1685 }
1686
1687 static int edl_seek(edl_record_ptr next_edl_record, demuxer_t* demuxer, demux_stream_t *d_audio, muxer_stream_t* mux_a, s_frame_data * frame_data, int framecopy) {
1688     sh_video_t * sh_video = demuxer->video ? demuxer->video->sh : NULL;
1689
1690     if (!sh_video) return 0;
1691     if (sh_video->pts >= next_edl_record->stop_sec) return 1; // nothing to do...
1692
1693     if (!edl_seek_type) {
1694         if(demux_seek(demuxer, next_edl_record->stop_sec - sh_video->pts, audio_delay, 0)){
1695             sh_video->pts = demuxer->video->pts;
1696             //if (vo_vobsub) vobsub_seek(vo_vobsub,sh_video->pts);
1697             resync_video_stream(sh_video);
1698             //if(vo_spudec) spudec_reset(vo_spudec);
1699             if (audio_delay != 0.0) fixdelay(demuxer->video, d_audio, mux_a, frame_data, framecopy);
1700             return 1;
1701         }
1702         // non-seekable stream.
1703         return 0;
1704     }
1705
1706     // slow seek, read every frame.
1707
1708     return slowseek(next_edl_record->stop_sec, demuxer->video, d_audio, mux_a, frame_data, framecopy, 1);
1709 }