lock trace bug, missed optimize in dvd_create, cin_quality=-1, motion plugin gui...
[goodguy/history.git] / cinelerra-5.1 / cinelerra / fileffmpeg.C
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 // work around for __STDC_CONSTANT_MACROS
8 #include <lzma.h>
9
10 #include "asset.h"
11 #include "bcwindowbase.h"
12 #include "bitspopup.h"
13 #include "ctype.h"
14 #include "ffmpeg.h"
15 #include "filebase.h"
16 #include "file.h"
17 #include "fileffmpeg.h"
18 #include "filesystem.h"
19 #include "indexfile.h"
20 #include "language.h"
21 #include "mainerror.h"
22 #include "mainprogress.h"
23 #include "mutex.h"
24 #include "preferences.h"
25 #include "videodevice.inc"
26
27 FileFFMPEG::FileFFMPEG(Asset *asset, File *file)
28   : FileBase(asset, file)
29 {
30         ff = 0;
31         if(asset->format == FILE_UNKNOWN)
32                 asset->format = FILE_FFMPEG;
33 }
34
35 FileFFMPEG::~FileFFMPEG()
36 {
37         delete ff;
38 }
39
40
41 FFMpegConfigNum::FFMpegConfigNum(BC_Window *window,
42                 int x, int y, char *title_text, int *output)
43  : BC_TumbleTextBox(window, (int64_t)*output,
44         (int64_t)-1, (int64_t)25000000, 100, y, 100)
45 {
46         this->window = window;
47         this->x = x;  this->y = y;
48         this->title_text = title_text;
49         this->output = output;
50 }
51
52 FFMpegConfigNum::~FFMpegConfigNum()
53 {
54 }
55
56 void FFMpegConfigNum::create_objects()
57 {
58         window->add_subwindow(title = new BC_Title(x, y, title_text));
59         BC_TumbleTextBox::create_objects();
60 }
61
62 int FFMpegConfigNum::update_param(const char *param, const char *opts)
63 {
64         char value[BCTEXTLEN];
65         if( !FileFFMPEG::get_ff_option(param, opts, value) ) {
66                 if( (*output = atol(value)) < 0 ) {
67                         disable(1);
68                         return 0;
69                 }
70                 BC_TumbleTextBox::update(value);
71         }
72         enable();
73         return 1;
74 }
75
76 int FFMpegConfigNum::handle_event()
77 {
78         *output = atol(get_text());
79         return 1;
80 }
81
82 FFMpegAudioNum::FFMpegAudioNum(BC_Window *window,
83                 int x, int y, char *title_text, int *output)
84  : FFMpegConfigNum(window, x, y, title_text, output)
85 {
86 }
87
88 int FFMpegAudioBitrate::handle_event()
89 {
90         int ret = FFMpegAudioNum::handle_event();
91         return ret;
92 }
93
94 FFMpegVideoNum::FFMpegVideoNum(BC_Window *window,
95                 int x, int y, char *title_text, int *output)
96  : FFMpegConfigNum(window, x, y, title_text, output)
97 {
98 }
99
100 int FFMpegVideoBitrate::handle_event()
101 {
102         int ret = FFMpegVideoNum::handle_event();
103         Asset *asset = window()->asset;
104         if( asset->ff_video_bitrate )
105                 window()->quality->disable();
106         else
107                 window()->quality->enable();
108         return ret;
109 }
110
111 int FFMpegVideoQuality::handle_event()
112 {
113         int ret = FFMpegVideoNum::handle_event();
114         Asset *asset = window()->asset;
115         if( asset->ff_video_quality )
116                 window()->bitrate->disable();
117         else
118                 window()->bitrate->enable();
119         return ret;
120 }
121
122 void FileFFMPEG::set_parameters(char *cp, int len, const char *bp)
123 {
124         char *ep = cp + len-2, ch = 0;
125         while( cp < ep && *bp != 0 ) { ch = *bp++; *cp++ = ch; }
126         if( ch != '\n' ) *cp++ = '\n';
127         *cp = 0;
128 }
129
130 void FileFFMPEG::get_parameters(BC_WindowBase *parent_window,
131                 Asset *asset, BC_WindowBase *&format_window,
132                 int audio_options, int video_options)
133 {
134         if(audio_options) {
135                 FFMPEGConfigAudio *window = new FFMPEGConfigAudio(parent_window, asset);
136                 format_window = window;
137                 window->create_objects();
138                 if( !window->run_window() )
139                         set_parameters(asset->ff_audio_options, sizeof(asset->ff_audio_options),
140                                  window->audio_options->get_text());
141                 delete window;
142         }
143         else if(video_options) {
144                 FFMPEGConfigVideo *window = new FFMPEGConfigVideo(parent_window, asset);
145                 format_window = window;
146                 window->create_objects();
147                 if( !window->run_window() )
148                         set_parameters(asset->ff_video_options, sizeof(asset->ff_video_options),
149                                  window->video_options->get_text());
150                 delete window;
151         }
152 }
153
154 int FileFFMPEG::check_sig(Asset *asset)
155 {
156         char *ptr = strstr(asset->path, ".pcm");
157         if( ptr ) return 0;
158         ptr = strstr(asset->path, ".raw");
159         if( ptr ) return 0;
160
161         FFMPEG ffmpeg(0);
162         int ret = !ffmpeg.init_decoder(asset->path) &&
163                 !ffmpeg.open_decoder() ? 1 : 0;
164         return ret;
165 }
166
167 void FileFFMPEG::get_info(char *path, char *text, int len)
168 {
169         char *cp = text;
170         FFMPEG ffmpeg(0);
171         cp += sprintf(cp, _("file path: %s\n"), path);
172         struct stat st;
173         int ret = 0;
174         if( stat(path, &st) < 0 ) {
175                 cp += sprintf(cp, _(" err: %s\n"), strerror(errno));
176                 ret = 1;
177         }
178         else {
179                 cp += sprintf(cp, _("  %jd bytes\n"), st.st_size);
180         }
181         if( !ret ) ret = ffmpeg.init_decoder(path);
182         if( !ret ) ret = ffmpeg.open_decoder();
183         if( !ret ) {
184                 cp += sprintf(cp, _("info:\n"));
185                 ffmpeg.info(cp, len-(cp-text));
186         }
187         else
188                 sprintf(cp, _("== open failed\n"));
189 }
190
191 int FileFFMPEG::get_video_info(int track, int &pid, double &framerate,
192                 int &width, int &height, char *title)
193 {
194         if( !ff ) return -1;
195         pid = ff->ff_video_pid(track);
196         framerate = ff->ff_frame_rate(track);
197         width = ff->ff_video_width(track);
198         height = ff->ff_video_height(track);
199         if( title ) *title = 0;
200         return 0;
201 }
202
203 int FileFFMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
204 {
205         if( !ff ) return 1;
206         return ff->ff_audio_for_video(vstream, astream, channel_mask);
207 }
208
209 int FileFFMPEG::select_video_stream(Asset *asset, int vstream)
210 {
211         if( !ff || !asset->video_data ) return 1;
212         asset->width = ff->ff_video_width(vstream);
213         asset->height = ff->ff_video_height(vstream);
214         asset->video_length = ff->ff_video_frames(vstream);
215         if( (asset->video_length = ff->ff_video_frames(vstream)) < 2 )
216                 asset->video_length = asset->video_length < 0 ? 0 : -1;
217         asset->frame_rate = ff->ff_frame_rate(vstream);
218         return 0;
219 }
220
221 int FileFFMPEG::select_audio_stream(Asset *asset, int astream)
222 {
223         if( !ff || !asset->audio_data ) return 1;
224         asset->sample_rate = ff->ff_sample_rate(astream);
225         asset->audio_length = ff->ff_audio_samples(astream);
226         return 0;
227 }
228
229 int FileFFMPEG::open_file(int rd, int wr)
230 {
231         int result = 0;
232         if( ff ) return 1;
233         ff = new FFMPEG(this);
234
235         if( rd ) {
236                 result = ff->init_decoder(asset->path);
237                 if( !result ) result = ff->open_decoder();
238                 if( !result ) {
239                         int audio_channels = ff->ff_total_audio_channels();
240                         if( audio_channels > 0 ) {
241                                 asset->audio_data = 1;
242                                 asset->channels = audio_channels;
243                                 asset->sample_rate = ff->ff_sample_rate(0);
244                                 asset->audio_length = ff->ff_audio_samples(0);
245                         }
246                         int video_layers = ff->ff_total_video_layers();
247                         if( video_layers > 0 ) {
248                                 asset->video_data = 1;
249                                 if( !asset->layers ) asset->layers = video_layers;
250                                 asset->actual_width = ff->ff_video_width(0);
251                                 asset->actual_height = ff->ff_video_height(0);
252                                 if( !asset->width ) asset->width = asset->actual_width;
253                                 if( !asset->height ) asset->height = asset->actual_height;
254                                 if( !asset->video_length &&
255                                     (asset->video_length = ff->ff_video_frames(0)) < 2 )
256                                         asset->video_length = asset->video_length < 0 ? 0 : -1;
257                                 if( !asset->frame_rate ) asset->frame_rate = ff->ff_frame_rate(0);
258                         }
259                         IndexState *index_state = asset->index_state;
260                         index_state->read_markers(file->preferences->index_directory, asset->path);
261                 }
262         }
263         else if( wr ) {
264                 result = ff->init_encoder(asset->path);
265                 // must be in this order or dvdauthor will fail
266                 if( !result && asset->video_data )
267                         result = ff->open_encoder("video", asset->vcodec);
268                 if( !result && asset->audio_data )
269                         result = ff->open_encoder("audio", asset->acodec);
270         }
271         return result;
272 }
273
274 int FileFFMPEG::close_file()
275 {
276         delete ff;
277         ff = 0;
278         return 0;
279 }
280
281
282 int FileFFMPEG::write_samples(double **buffer, int64_t len)
283 {
284         if( !ff || len < 0 ) return -1;
285         int stream = 0;
286         int ret = ff->encode(stream, buffer, len);
287         return ret;
288 }
289
290 int FileFFMPEG::write_frames(VFrame ***frames, int len)
291 {
292         if( !ff ) return -1;
293         int ret = 0, layer = 0;
294         for(int i = 0; i < 1; i++) {
295                 for(int j = 0; j < len && !ret; j++) {
296                         VFrame *frame = frames[i][j];
297                         ret = ff->encode(layer, frame);
298                 }
299         }
300         return ret;
301 }
302
303
304 int FileFFMPEG::read_samples(double *buffer, int64_t len)
305 {
306         if( !ff || len < 0 ) return -1;
307         int ch = file->current_channel;
308         int64_t pos = file->current_sample;
309         int ret = ff->decode(ch, pos, buffer, len);
310         if( ret > 0 ) return 0;
311         memset(buffer,0,len*sizeof(*buffer));
312         return -1;
313 }
314
315 int FileFFMPEG::read_frame(VFrame *frame)
316 {
317         if( !ff ) return -1;
318         int layer = file->current_layer;
319         int64_t pos = asset->video_length >= 0 ? file->current_frame : 0;
320         int ret = ff->decode(layer, pos, frame);
321         frame->set_status(ret);
322         if( ret >= 0 ) return 0;
323         frame->clear_frame();
324         return -1;
325 }
326
327
328 int64_t FileFFMPEG::get_memory_usage()
329 {
330         return 0;
331 }
332
333 int FileFFMPEG::colormodel_supported(int colormodel)
334 {
335         return colormodel;
336 }
337
338 int FileFFMPEG::get_best_colormodel(Asset *asset, int driver)
339 {
340         switch(driver) {
341         case PLAYBACK_X11:
342                 return BC_RGB888;
343         case PLAYBACK_X11_XV:
344         case PLAYBACK_ASYNCHRONOUS:
345                 return BC_YUV888;
346         case PLAYBACK_X11_GL:
347                 return BC_YUV888;
348         case PLAYBACK_DV1394:
349         case PLAYBACK_FIREWIRE:
350                 return BC_YUV422P;
351         case VIDEO4LINUX2:
352                 return BC_RGB888;
353         case VIDEO4LINUX2JPEG:
354                 return BC_COMPRESSED;
355         case CAPTURE_DVB:
356         case VIDEO4LINUX2MPEG:
357                 return BC_YUV422P;
358         case CAPTURE_JPEG_WEBCAM:
359                 return BC_COMPRESSED;
360         case CAPTURE_YUYV_WEBCAM:
361                 return BC_YUV422;
362         case CAPTURE_FIREWIRE:
363         case CAPTURE_IEC61883:
364                 return BC_YUV422P;
365         }
366
367         return BC_RGB888;
368 }
369
370
371 int FileFFMPEG::get_ff_option(const char *nm, const char *options, char *value)
372 {
373         for( const char *cp=options; *cp!=0; ) {
374                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
375                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
376                 if( *cp ) ++cp;
377                 *bp = 0;
378                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
379                 char key[BCSTRLEN], val[BCTEXTLEN];
380                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
381                 if( !strcmp(key, nm) ) {
382                         strcpy(value, val);
383                         return 0;
384                 }
385         }
386         return 1;
387 }
388
389 //======
390
391 FFMPEGConfigAudio::FFMPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
392  : BC_Window(_(PROGRAM_NAME ": Audio Preset"),
393         parent_window->get_abs_cursor_x(1),
394         parent_window->get_abs_cursor_y(1),
395         420, 420)
396 {
397         this->parent_window = parent_window;
398         this->asset = asset;
399         preset_popup = 0;
400
401         bitrate = 0;
402         audio_options = 0;
403         ff_options_dialog = 0;
404 }
405
406 FFMPEGConfigAudio::~FFMPEGConfigAudio()
407 {
408         delete ff_options_dialog;
409         lock_window("FFMPEGConfigAudio::~FFMPEGConfigAudio");
410         delete preset_popup;
411         presets.remove_all_objects();
412         unlock_window();
413 }
414
415 void FFMPEGConfigAudio::create_objects()
416 {
417         int x = 10, y = 10;
418         lock_window("FFMPEGConfigAudio::create_objects");
419
420         FileSystem fs;
421         char option_path[BCTEXTLEN];
422         FFMPEG::set_option_path(option_path, "audio");
423         fs.update(option_path);
424         int total_files = fs.total_files();
425         for(int i = 0; i < total_files; i++) {
426                 const char *name = fs.get_entry(i)->get_name();
427                 if( asset->fformat[0] != 0 ) {
428                         const char *ext = strrchr(name,'.');
429                         if( !ext ) continue;
430                         if( strcmp(asset->fformat, ++ext) ) continue;
431                 }
432                 presets.append(new BC_ListBoxItem(name));
433         }
434
435         if( asset->acodec[0] ) {
436                 int k = presets.size();
437                 while( --k >= 0 && strcmp(asset->acodec, presets[k]->get_text()) );
438                 if( k < 0 ) asset->acodec[0] = 0;
439         }
440
441         if( !asset->acodec[0] && presets.size() > 0 )
442                 strcpy(asset->acodec, presets[0]->get_text());
443
444         add_tool(new BC_Title(x, y, _("Preset:")));
445         y += 25;
446         preset_popup = new FFMPEGConfigAudioPopup(this, x, y);
447         preset_popup->create_objects();
448
449         y += 50;
450         bitrate = new FFMpegAudioBitrate(this, x, y, _("Bitrate:"), &asset->ff_audio_bitrate);
451         bitrate->create_objects();
452         bitrate->set_increment(1000);
453
454         y += bitrate->get_h() + 10;
455         BC_Title *title = new BC_Title(x, y, _("Audio Options:"));
456         add_subwindow(title);
457
458         ff_options_dialog = new FFOptionsAudioDialog(this);
459         int x1 = x + title->get_w() + 8;
460         add_subwindow(new FFOptionsViewAudio(this, x1, y, _("view")));
461
462         y += 25;
463         if( !asset->ff_audio_options[0] && asset->acodec[0] ) {
464                 FFMPEG::set_option_path(option_path, "audio/%s", asset->acodec);
465                 FFMPEG::load_options(option_path, asset->ff_audio_options,
466                          sizeof(asset->ff_audio_options));
467         }
468
469         audio_options = new FFAudioOptions(this, x, y, get_w()-x-20, 10,
470                  sizeof(asset->ff_audio_options)-1, asset->ff_audio_options);
471         audio_options->create_objects();
472         add_subwindow(new BC_OKButton(this));
473         add_subwindow(new BC_CancelButton(this));
474
475         bitrate->update_param("cin_bitrate", asset->ff_audio_options);
476
477         show_window(1);
478         bitrate->handle_event();
479         unlock_window();
480 }
481
482 int FFMPEGConfigAudio::close_event()
483 {
484         set_done(1);
485         return 1;
486 }
487
488 FFAudioOptions::FFAudioOptions(FFMPEGConfigAudio *audio_popup,
489         int x, int y, int w, int rows, int size, char *text)
490  : BC_ScrollTextBox(audio_popup, x, y, w, rows, text, size)
491 {
492         this->audio_popup = audio_popup;
493 }
494
495
496 FFMPEGConfigAudioPopup::FFMPEGConfigAudioPopup(FFMPEGConfigAudio *popup, int x, int y)
497  : BC_PopupTextBox(popup, &popup->presets, popup->asset->acodec, x, y, 300, 300)
498 {
499         this->popup = popup;
500 }
501
502 int FFMPEGConfigAudioPopup::handle_event()
503 {
504         strcpy(popup->asset->acodec, get_text());
505         Asset *asset = popup->asset;
506         char option_path[BCTEXTLEN];
507         FFMPEG::set_option_path(option_path, "audio/%s", asset->acodec);
508         FFMPEG::load_options(option_path, asset->ff_audio_options,
509                          sizeof(asset->ff_audio_options));
510         popup->audio_options->update(asset->ff_audio_options);
511         popup->audio_options->set_text_row(0);
512
513         popup->bitrate->update_param("cin_bitrate", asset->ff_audio_options);
514         return 1;
515 }
516
517
518 FFMPEGConfigAudioToggle::FFMPEGConfigAudioToggle(FFMPEGConfigAudio *popup,
519         char *title_text, int x, int y, int *output)
520  : BC_CheckBox(x, y, *output, title_text)
521 {
522         this->popup = popup;
523         this->output = output;
524 }
525 int FFMPEGConfigAudioToggle::handle_event()
526 {
527         *output = get_value();
528         return 1;
529 }
530
531 //======
532
533 FFMPEGConfigVideo::FFMPEGConfigVideo(BC_WindowBase *parent_window, Asset *asset)
534  : BC_Window(_(PROGRAM_NAME ": Video Preset"),
535         parent_window->get_abs_cursor_x(1),
536         parent_window->get_abs_cursor_y(1),
537         420, 420)
538 {
539         this->parent_window = parent_window;
540         this->asset = asset;
541         preset_popup = 0;
542
543         bitrate = 0;
544         quality = 0;
545         video_options = 0;
546 }
547
548 FFMPEGConfigVideo::~FFMPEGConfigVideo()
549 {
550         delete ff_options_dialog;
551         lock_window("FFMPEGConfigVideo::~FFMPEGConfigVideo");
552         if(preset_popup) delete preset_popup;
553         presets.remove_all_objects();
554         unlock_window();
555 }
556
557 void FFMPEGConfigVideo::create_objects()
558 {
559         int x = 10, y = 10;
560         lock_window("FFMPEGConfigVideo::create_objects");
561
562         add_subwindow(new BC_Title(x, y, _("Compression:")));
563         y += 25;
564
565         FileSystem fs;
566         char option_path[BCTEXTLEN];
567         FFMPEG::set_option_path(option_path, "video");
568         fs.update(option_path);
569         int total_files = fs.total_files();
570         for(int i = 0; i < total_files; i++) {
571                 const char *name = fs.get_entry(i)->get_name();
572                 if( asset->fformat[0] != 0 ) {
573                         const char *ext = strrchr(name,'.');
574                         if( !ext ) continue;
575                         if( strcmp(asset->fformat, ++ext) ) continue;
576                 }
577                 presets.append(new BC_ListBoxItem(name));
578         }
579
580         if( asset->vcodec[0] ) {
581                 int k = presets.size();
582                 while( --k >= 0 && strcmp(asset->vcodec, presets[k]->get_text()) );
583                 if( k < 0 ) asset->vcodec[0] = 0;
584         }
585
586         if( !asset->vcodec[0] && presets.size() > 0 )
587                 strcpy(asset->vcodec, presets[0]->get_text());
588
589         preset_popup = new FFMPEGConfigVideoPopup(this, x, y);
590         preset_popup->create_objects();
591
592         if( asset->ff_video_bitrate && asset->ff_video_quality ) {
593                 asset->ff_video_bitrate = 0;
594                 asset->ff_video_quality = 0;
595         }
596
597         y += 50;
598         bitrate = new FFMpegVideoBitrate(this, x, y, _("Bitrate:"), &asset->ff_video_bitrate);
599         bitrate->create_objects();
600         bitrate->set_increment(100000);
601         y += bitrate->get_h() + 5;
602         quality = new FFMpegVideoQuality(this, x, y, _("Quality:"), &asset->ff_video_quality);
603         quality->create_objects();
604         quality->set_increment(1);
605         quality->set_boundaries((int64_t)0, (int64_t)31);
606
607         y += quality->get_h() + 10;
608         BC_Title *title = new BC_Title(x, y, _("Video Options:"));
609         add_subwindow(title);
610
611         ff_options_dialog = new FFOptionsVideoDialog(this);
612         int x1 = x + title->get_w() + 8;
613         add_subwindow(new FFOptionsViewVideo(this, x1, y, _("view")));
614
615         y += 25;
616         if( !asset->ff_video_options[0] && asset->vcodec[0] ) {
617                 FFMPEG::set_option_path(option_path, "video/%s", asset->vcodec);
618                 FFMPEG::load_options(option_path, asset->ff_video_options,
619                          sizeof(asset->ff_video_options));
620         }
621
622         video_options = new FFVideoOptions(this, x, y, get_w()-x-20, 10,
623                  sizeof(asset->ff_video_options)-1, asset->ff_video_options);
624         video_options->create_objects();
625         add_subwindow(new BC_OKButton(this));
626         add_subwindow(new BC_CancelButton(this));
627
628         bitrate->update_param("cin_bitrate", asset->ff_video_options);
629         quality->update_param("cin_quality", asset->ff_video_options);
630
631         show_window(1);
632         if( asset->ff_video_bitrate )
633                 quality->disable();
634         if( asset->ff_video_quality )
635                 bitrate->disable();
636         unlock_window();
637 }
638
639 int FFMPEGConfigVideo::close_event()
640 {
641         set_done(1);
642         return 1;
643 }
644
645 FFVideoOptions::FFVideoOptions(FFMPEGConfigVideo *video_popup,
646         int x, int y, int w, int rows, int size, char *text)
647  : BC_ScrollTextBox(video_popup, x, y, w, rows, text, size)
648 {
649         this->video_popup = video_popup;
650 }
651
652
653 FFMPEGConfigVideoPopup::FFMPEGConfigVideoPopup(FFMPEGConfigVideo *popup, int x, int y)
654  : BC_PopupTextBox(popup, &popup->presets, popup->asset->vcodec, x, y, 300, 300)
655 {
656         this->popup = popup;
657 }
658
659 int FFMPEGConfigVideoPopup::handle_event()
660 {
661         strcpy(popup->asset->vcodec, get_text());
662         Asset *asset = popup->asset;
663         char option_path[BCTEXTLEN];
664         FFMPEG::set_option_path(option_path, "video/%s", asset->vcodec);
665         FFMPEG::load_options(option_path, asset->ff_video_options,
666                          sizeof(asset->ff_video_options));
667         popup->video_options->update(asset->ff_video_options);
668         popup->video_options->set_text_row(0);
669
670         popup->bitrate->update_param("cin_bitrate", asset->ff_video_options);
671         popup->quality->update_param("cin_quality", asset->ff_video_options);
672         return 1;
673 }
674
675
676 FFMPEGConfigVideoToggle::FFMPEGConfigVideoToggle(FFMPEGConfigVideo *popup,
677         char *title_text, int x, int y, int *output)
678  : BC_CheckBox(x, y, *output, title_text)
679 {
680         this->popup = popup;
681         this->output = output;
682 }
683 int FFMPEGConfigVideoToggle::handle_event()
684 {
685         *output = get_value();
686         return 1;
687 }
688
689 FFMPEGScanProgress::FFMPEGScanProgress(IndexFile *index_file, MainProgressBar *progress_bar,
690                 const char *title, int64_t length, int64_t *position, int *canceled)
691  : Thread(1, 0, 0)
692 {
693         this->index_file = index_file;
694         this->progress_bar = progress_bar;
695         strcpy(this->progress_title, title);
696         this->length = length;
697         this->position = position;
698         this->canceled = canceled;
699         done = 0;
700         start();
701 }
702
703 FFMPEGScanProgress::~FFMPEGScanProgress()
704 {
705         done = 1;
706         cancel();
707         join();
708 }
709
710 void FFMPEGScanProgress::run()
711 {
712         while( !done ) {
713                 if( progress_bar->update(*position) ) {
714                         *canceled = done = 1;
715                         break;
716                 }
717                 index_file->redraw_edits(0);
718                 usleep(500000);
719         }
720 }
721
722 int FileFFMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
723 {
724         if( !ff ) return -1;
725         if( !file->preferences->ffmpeg_marker_indexes ) return 1;
726
727         IndexState *index_state = index_file->get_state();
728         if( index_state->index_status != INDEX_NOTTESTED ) return 0;
729         index_state->reset_index();
730         index_state->reset_markers();
731         index_state->index_status = INDEX_BUILDING;
732
733         for( int aidx=0; aidx<ff->ffaudio.size(); ++aidx ) {
734                 FFAudioStream *aud = ff->ffaudio[aidx];
735                 index_state->add_audio_stream(aud->channels, aud->length);
736         }
737
738         FileSystem fs;
739         int64_t file_bytes = fs.get_size(ff->fmt_ctx->filename);
740         char *index_path = index_file->index_filename;
741
742         int canceled = 0;
743         int64_t scan_position = 0;
744         FFMPEGScanProgress *scan_progress = 0;
745         if( progress_bar ) {
746                 char progress_title[BCTEXTLEN];
747                 sprintf(progress_title, _("Creating %s\n"), index_path);
748                 progress_bar->update_title(progress_title, 1);
749                 progress_bar->update_length(file_bytes);
750                 scan_progress = new FFMPEGScanProgress(index_file,
751                                 progress_bar, progress_title, file_bytes,
752                                 &scan_position, &canceled);
753         }
754
755         index_state->index_bytes = file_bytes;
756         index_state->init_scan(file->preferences->index_size);
757
758         if( ff->scan(index_state, &scan_position, &canceled) || canceled ) {
759                 index_state->reset_index();
760                 index_state->reset_markers();
761                 canceled = 1;
762         }
763
764         delete scan_progress;
765         if( canceled ) return 1;
766
767         index_state->marker_status = MARKERS_READY;
768         return index_state->create_index(index_path, asset);
769 }
770
771
772 FFOptions_OptPanel::
773 FFOptions_OptPanel(FFOptionsWindow *fwin, int x, int y, int w, int h)
774  : BC_ListBox(x, y, w, h, LISTBOX_TEXT), opts(items[0]), vals(items[1])
775 {
776         this->fwin = fwin;
777         update();  // init col/wid/columns
778 }
779
780 FFOptions_OptPanel::
781 ~FFOptions_OptPanel()
782 {
783 }
784
785 void FFOptions_OptPanel::create_objects()
786 {
787         const char *cols[] = { _("option"), _("value"), };
788         const int col1_w = 150;
789         int wids[] = { col1_w, get_w()-col1_w };
790         BC_ListBox::update(&items[0], &cols[0], &wids[0], sizeof(items)/sizeof(items[0]));
791 }
792
793 int FFOptions_OptPanel::update()
794 {
795         opts.remove_all();
796         vals.remove_all();
797         FFOptions &options = fwin->options;
798         for( int i=0; i<options.size(); ++i ) {
799                 FFOptions_Opt *opt = options[i];
800                 opts.append(opt->item_name);
801                 vals.append(opt->item_value);
802         }
803         draw_items(1);
804         return 0;
805 }
806
807 int FFOptions_OptPanel::cursor_leave_event()
808 {
809         hide_tooltip();
810         return 0;
811 }
812
813
814 FFOptions_OptName::FFOptions_OptName(FFOptions_Opt *opt, const char *nm)
815 {
816         this->opt = opt;
817         set_text(nm);
818 }
819
820 FFOptions_OptName::~FFOptions_OptName()
821 {
822 }
823
824 FFOptions_OptValue::FFOptions_OptValue(FFOptions_Opt *opt)
825 {
826         this->opt = opt;
827 }
828
829
830 void FFOptions_OptValue::update()
831 {
832         if( !opt ) return;
833         char val[BCTEXTLEN];  val[0] = 0;
834         opt->get(val, sizeof(val));
835         update(val);
836 }
837
838 void FFOptions_OptValue::update(const char *v)
839 {
840         set_text(v);
841 }
842
843 FFOptions_Opt::FFOptions_Opt(FFOptions *options, const AVOption *opt, const char *nm)
844 {
845         this->options = options;
846         this->opt = opt;
847         item_name = new FFOptions_OptName(this, nm);
848         item_value = new FFOptions_OptValue(this);
849 }
850
851 FFOptions_Opt::~FFOptions_Opt()
852 {
853         delete item_name;
854         delete item_value;
855 }
856
857 char *FFOptions_Opt::get(char *vp, int sz)
858 {
859         char *cp = vp;
860         *cp = 0;
861         if( !opt ) return cp;
862
863         void *obj = (void *)options->obj;
864         uint8_t *bp = 0;
865         if( av_opt_get(obj, opt->name, 0, &bp) >= 0 && bp != 0 ) {
866                 const char *val = (const char *)bp;
867                 if( opt->unit && *val ) {
868                         int id = atoi(val);
869                         const char *uid = unit_name(id);
870                         if( uid ) val = uid;
871                 }
872                 cp = sz >= 0 ? strncpy(vp,val,sz) : strcpy(vp, val);
873                 if( sz > 0 ) vp[sz-1] = 0;
874                 av_freep(&bp);
875         }
876
877         return cp;
878 }
879
880 void FFOptions_Opt::set(const char *val)
881 {
882         void *obj = (void *)options->obj;
883         if( !obj || !opt ) return;
884         av_opt_set(obj, opt->name, val, 0);
885 }
886
887
888 FFOptionsKindItem::FFOptionsKindItem(FFOptionsKind *kind, const char *text, int idx)
889  : BC_MenuItem(text)
890 {
891         this->kind = kind;
892         this->idx = idx;
893 }
894
895 FFOptionsKindItem::~FFOptionsKindItem()
896 {
897 }
898
899 int FFOptionsKindItem::handle_event()
900 {
901         FFOptionsWindow *fwin = kind->fwin;
902         FFOptions &options = fwin->options;
903         options.initialize(fwin, idx);
904         fwin->draw();
905         return 1;
906 }
907
908 const char *FFOptionsKind::kinds[] = {
909         N_("codec"),    // FF_KIND_CODEC
910         N_("ffmpeg"),   // FF_KIND_FFMPEG
911 };
912
913 FFOptionsKind::
914 FFOptionsKind(FFOptionsWindow *fwin, int x, int y, int w)
915  : BC_PopupMenu(x, y, w-calculate_w(0), "")
916 {
917         this->fwin = fwin;
918 }
919
920 FFOptionsKind::
921 ~FFOptionsKind()
922 {
923 }
924
925 void FFOptionsKind::create_objects()
926 {
927         for( int i=0; i<(int)(sizeof(kinds)/sizeof(kinds[0])); ++i )
928                 add_item(new FFOptionsKindItem(this, _(kinds[i]), i));
929 }
930
931 int FFOptionsKind::handle_event()
932 {
933         return 1;
934 }
935
936 void FFOptionsKind::set(int k)
937 {
938         this->kind = k;
939         set_text(_(kinds[k]));
940 }
941
942 FFOptionsText::
943 FFOptionsText(FFOptionsWindow *fwin, int x, int y, int w)
944  : BC_TextBox(x, y, w, 1, (char *)"")
945 {
946         this->fwin = fwin;
947 }
948
949 FFOptionsText::
950 ~FFOptionsText()
951 {
952 }
953
954 int FFOptionsText::handle_event()
955 {
956         return 0;
957 }
958
959 FFOptionsUnits::
960 FFOptionsUnits(FFOptionsWindow *fwin, int x, int y, int w)
961  : BC_PopupMenu(x, y, w, "")
962 {
963         this->fwin = fwin;
964 }
965
966 FFOptionsUnits::
967 ~FFOptionsUnits()
968 {
969 }
970
971 int FFOptionsUnits::handle_event()
972 {
973         const char *text = get_text();
974         if( text && fwin->selected ) {
975                 fwin->selected->set(text);
976                 fwin->selected->item_value->update();
977                 av_dict_set(&fwin->dialog->ff_opts,
978                         fwin->selected->item_name->get_text(),
979                         fwin->selected->item_value->get_text(), 0);
980                 fwin->draw();
981         }
982         return 1;
983 }
984
985 FFOptionsApply::
986 FFOptionsApply(FFOptionsWindow *fwin, int x, int y)
987  : BC_GenericButton(x, y, _("Apply"))
988 {
989         this->fwin = fwin;
990 }
991
992 FFOptionsApply::
993 ~FFOptionsApply()
994 {
995 }
996
997 int FFOptionsApply::handle_event()
998 {
999         const char *text = fwin->text->get_text();
1000         if( text && fwin->selected ) {
1001                 fwin->selected->set(text);
1002                 fwin->selected->item_value->update();
1003                 av_dict_set(&fwin->dialog->ff_opts,
1004                         fwin->selected->item_name->get_text(),
1005                         fwin->selected->item_value->get_text(), 0);
1006                 fwin->draw();
1007         }
1008         return 1;
1009 }
1010
1011 FFOptions::FFOptions()
1012 {
1013         avctx = 0;
1014         obj = 0;
1015 }
1016
1017 FFOptions::~FFOptions()
1018 {
1019         remove_all_objects();
1020         avcodec_free_context(&avctx);
1021 }
1022
1023 int FFOptions::cmpr(const void *a, const void *b)
1024 {
1025         FFOptions_Opt *ap = *(FFOptions_Opt **)a;
1026         FFOptions_Opt *bp = *(FFOptions_Opt **)b;
1027         const char *vap = ap->item_name->get_text();
1028         const char *vbp = bp->item_name->get_text();
1029         return strcmp(vap, vbp);
1030 }
1031
1032 void FFOptions::initialize(FFOptionsWindow *win, int kind)
1033 {
1034         remove_all_objects();
1035         this->win = win;
1036         win->selected = 0;
1037         obj = 0;
1038         if( !avctx )
1039                 avctx = avcodec_alloc_context3(win->dialog->codec);
1040
1041         switch( kind ) {
1042         case FF_KIND_CODEC:
1043                 obj = (const void *)avctx->priv_data;
1044                 break;
1045         case FF_KIND_FFMPEG:
1046                 obj = (const void *)avctx;
1047                 break;
1048         }
1049
1050         if( obj ) {
1051                 FFOptions &conf = *this;
1052                 const AVOption *opt = 0;
1053                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
1054                         if( opt->type == AV_OPT_TYPE_CONST ) continue;
1055                         int dupl = 0;
1056                         for( int i=0; !dupl && i<size(); ++i ) {
1057                                 FFOptions_Opt *fopt = conf[i];
1058                                 const AVOption *op = fopt->opt;
1059                                 if( op->offset != opt->offset ) continue;
1060                                 if( op->type != opt->type ) continue;
1061                                 dupl = 1;
1062                                 if( strlen(op->name) < strlen(opt->name) )
1063                                         fopt->opt = opt;
1064                         }
1065                         if( dupl ) continue;
1066                         FFOptions_Opt *fopt = new FFOptions_Opt(this, opt, opt->name);
1067                         append(fopt);
1068                         char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1069                         fopt->item_value->update(vp);
1070                 }
1071         }
1072
1073         qsort(&values[0],size(),sizeof(values[0]),cmpr);
1074         win->kind->set(kind);
1075         win->panel->update();
1076         win->panel->set_yposition(0);
1077 }
1078
1079 int FFOptions::update()
1080 {
1081         int ret = 0;
1082         FFOptions &conf = *this;
1083
1084         for( int i=0; i<size(); ++i ) {
1085                 FFOptions_Opt *fopt = conf[i];
1086                 char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1087                 if( !vp || !strcmp(val, fopt->item_value->get_text()) ) continue;
1088                 fopt->item_value->update(val);
1089                 ++ret;
1090         }
1091         return ret;
1092 }
1093
1094 void FFOptions::dump(FILE *fp)
1095 {
1096         if( !obj ) return;
1097         const AVOption *opt = 0;
1098         FFOptions &conf = *this;
1099
1100         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1101                 if( opt->type == AV_OPT_TYPE_CONST ) continue;
1102                 int k = size();
1103                 while( --k >= 0 && strcmp(opt->name, conf[k]->opt->name) );
1104                 if( k < 0 ) continue;
1105                 FFOptions_Opt *fopt = conf[k];
1106                 char val[BCTEXTLEN], *vp = fopt->get(val,sizeof(val));
1107                 fprintf(fp, "  %s:=%s", opt->name, vp);
1108                 if( opt->unit ) {
1109                         char unt[BCTEXTLEN], *up = unt;
1110                         fopt->units(up);
1111                         fprintf(fp, "%s", unt);
1112                 }
1113                 fprintf(fp, "\n");
1114         }
1115 }
1116
1117
1118 void FFOptionsWindow::update(FFOptions_Opt *opt)
1119 {
1120         if( selected != opt ) {
1121                 if( selected ) selected->item_name->set_selected(0);
1122                 selected = opt;
1123                 if( selected ) selected->item_name->set_selected(1);
1124         }
1125         clear_box(0,0, 0,panel->get_y());
1126         char str[BCTEXTLEN], *sp;
1127         *(sp=str) = 0;
1128         if( opt ) opt->types(sp);
1129         type->update(str);
1130         *(sp=str) = 0;
1131         if( opt ) opt->ranges(sp);
1132         range->update(str);
1133         while( units->total_items() ) units->del_item(0);
1134         char unit[BCSTRLEN];  strcpy(unit, "()");
1135         if( opt && opt->opt ) {
1136                 ArrayList<const char *> names;
1137                 int n = 0;
1138                 if( opt->opt->unit ) {
1139                         n = opt->units(names);
1140                         if( n > 0 ) strcpy(unit,opt->opt->unit);
1141                 }
1142                 for( int i=0; i<n; ++i )
1143                         units->add_item(new BC_MenuItem(names[i], 0));
1144         }
1145         units->set_text(unit);
1146         char val[BCTEXTLEN];  val[0] = 0;
1147         if( opt ) opt->get(val, sizeof(val));
1148         text->update(val);
1149
1150         panel->update();
1151 }
1152
1153 void FFOptions_OptPanel::show_tip(const char *tip)
1154 {
1155         if( !tip ) return;
1156         int len = strlen(tip);
1157         if( len > (int)sizeof(tip_text)-1 ) len = sizeof(tip_text)-1;
1158         strncpy(tip_text,tip,len);
1159         tip_text[len] = 0;
1160         int line_limit = 60;
1161         int limit2 = line_limit/2;
1162         int limit4 = line_limit/4-2;
1163         char *cp = tip_text, *dp = cp+len;
1164         int n;  char *bp, *ep, *pp, *sp;
1165         while( cp < dp ) {
1166                 for( ep=cp; ep<dp && *ep!='\n'; ++ep );
1167                 // target about half remaining line, constrain line_limit
1168                 if( (n=(ep-1-cp)/2) < limit2 || n > line_limit )
1169                         n = line_limit;
1170                 // search for last punct, last space before line_limit
1171                 for( bp=cp, pp=sp=0; --n>=0 && cp<ep; ++cp ) {
1172                         if( ispunct(*cp) && isspace(*(cp+1)) ) pp = cp;
1173                         else if( isspace(*cp) ) sp = cp;
1174                 }
1175                 // line not empty
1176                 if( cp < ep ) {
1177                         // first, after punctuation
1178                         if( pp && pp-bp >= limit4 )
1179                                 cp = pp+1;
1180                         // then, on spaces
1181                         else if( sp ) {
1182                                 cp = sp;
1183                         }
1184                         // last, on next space
1185                         else {
1186                                 while( cp<dp && !isspace(*cp) ) ++cp;
1187                         }
1188                         // add new line
1189                         if( !*cp ) break;
1190                         *cp++ = '\n';
1191                 }
1192         }
1193         fwin->panel->set_tooltip(tip_text);
1194         fwin->panel->show_tooltip();
1195 }
1196
1197 int FFOptions_OptPanel::selection_changed()
1198 {
1199         FFOptions_Opt *opt = 0;
1200         BC_ListBoxItem *item = get_selection(0, 0);
1201         if( item ) {
1202                 FFOptions_OptName *opt_name = (FFOptions_OptName *)item;
1203                 opt = opt_name->opt;
1204         }
1205         fwin->update(opt);
1206         if( opt ) show_tip(opt->tip());
1207         return 1;
1208 }
1209
1210
1211 int FFOptions_Opt::types(char *rp)
1212 {
1213         const char *cp = "";
1214         if( opt ) switch (opt->type) {
1215         case AV_OPT_TYPE_FLAGS: cp = N_("<flags>");  break;
1216         case AV_OPT_TYPE_INT: cp = N_("<int>"); break;
1217         case AV_OPT_TYPE_INT64: cp = N_("<int64>"); break;
1218         case AV_OPT_TYPE_DOUBLE: cp = N_("<double>"); break;
1219         case AV_OPT_TYPE_FLOAT: cp = N_("<float>"); break;
1220         case AV_OPT_TYPE_STRING: cp = N_("<string>"); break;
1221         case AV_OPT_TYPE_RATIONAL: cp = N_("<rational>"); break;
1222         case AV_OPT_TYPE_BINARY: cp = N_("<binary>"); break;
1223         case AV_OPT_TYPE_IMAGE_SIZE: cp = N_("<image_size>"); break;
1224         case AV_OPT_TYPE_VIDEO_RATE: cp = N_("<video_rate>"); break;
1225         case AV_OPT_TYPE_PIXEL_FMT: cp = N_("<pix_fmt>"); break;
1226         case AV_OPT_TYPE_SAMPLE_FMT: cp = N_("<sample_fmt>"); break;
1227         case AV_OPT_TYPE_DURATION: cp = N_("<duration>"); break;
1228         case AV_OPT_TYPE_COLOR: cp = N_("<color>"); break;
1229         case AV_OPT_TYPE_CHANNEL_LAYOUT: cp = N_("<channel_layout>");  break;
1230         case AV_OPT_TYPE_BOOL: cp = N_("<bool>");  break;
1231         default: cp = N_("<undef>");  break;
1232         }
1233         return sprintf(rp, "%s", _(cp));
1234 }
1235 int FFOptions_Opt::scalar(double d, char *rp)
1236 {
1237         const char *cp = 0;
1238              if( d == INT_MAX ) cp = "INT_MAX";
1239         else if( d == INT_MIN ) cp = "INT_MIN";
1240         else if( d == UINT32_MAX ) cp = "UINT32_MAX";
1241         else if( d == (double)INT64_MAX ) cp = "I64_MAX";
1242         else if( d == INT64_MIN ) cp = "I64_MIN";
1243         else if( d == FLT_MAX ) cp = "FLT_MAX";
1244         else if( d == FLT_MIN ) cp = "FLT_MIN";
1245         else if( d == -FLT_MAX ) cp = "-FLT_MAX";
1246         else if( d == -FLT_MIN ) cp = "-FLT_MIN";
1247         else if( d == DBL_MAX ) cp = "DBL_MAX";
1248         else if( d == DBL_MIN ) cp = "DBL_MIN";
1249         else if( d == -DBL_MAX ) cp = "-DBL_MAX";
1250         else if( d == -DBL_MIN ) cp = "-DBL_MIN";
1251         else if( d == 0 ) cp = signbit(d) ? "-0" : "0";
1252         else if( isnan(d) ) cp = signbit(d) ? "-NAN" : "NAN";
1253         else if( isinf(d) ) cp = signbit(d) ? "-INF" : "INF";
1254         else return sprintf(rp, "%g", d);
1255         return sprintf(rp, "%s", cp);
1256 }
1257
1258 int FFOptions_Opt::ranges(char *rp)
1259 {
1260         if( !opt ) return 0;
1261         void *obj = (void *)options->obj;
1262         if( !obj ) return 0;
1263
1264         switch (opt->type) {
1265         case AV_OPT_TYPE_INT:
1266         case AV_OPT_TYPE_INT64:
1267         case AV_OPT_TYPE_DOUBLE:
1268         case AV_OPT_TYPE_FLOAT: break;
1269         default: return 0;;
1270         }
1271         AVOptionRanges *r = 0;
1272         char *cp = rp;
1273         if( av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) < 0 ) return 0;
1274         for( int i=0; i<r->nb_ranges; ++i ) {
1275                 cp += sprintf(cp, " (");  cp += scalar(r->range[i]->value_min, cp);
1276                 cp += sprintf(cp, "..");  cp += scalar(r->range[i]->value_max, cp);
1277                 cp += sprintf(cp, ")");
1278         }
1279         av_opt_freep_ranges(&r);
1280         return cp - rp;
1281 }
1282
1283 int FFOptions_Opt::units(ArrayList<const char *> &names)
1284 {
1285         if( !opt || !opt->unit ) return 0;
1286         const void *obj = options->obj;
1287         if( !obj ) return 0;
1288
1289         ArrayList<const AVOption *> opts;
1290         const AVOption *opt = NULL;
1291         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1292                 if( !opt->unit ) continue;
1293                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1294                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1295                 int i = opts.size();
1296                 while( --i >= 0 ) {
1297                         if( opts[i]->default_val.i64 != opt->default_val.i64 ) continue;
1298                         if( strlen(opts[i]->name) < strlen(opt->name) ) opts[i] = opt;
1299                         break;
1300                 }
1301                 if( i >= 0 ) continue;
1302                 opts.append(opt);
1303         }
1304
1305         for( int i=0; i<opts.size(); ++i )
1306                 names.append(opts[i]->name);
1307
1308         return names.size();
1309 }
1310
1311 int FFOptions_Opt::units(char *rp)
1312 {
1313         ArrayList<const char *> names;
1314         int n = units(names);
1315         if( !n ) return 0;
1316         char *cp = rp;
1317         cp += sprintf(cp, " [%s:", this->opt->unit);
1318         for( int i=0; i<n; ++i )
1319                 cp += sprintf(cp, " %s", names[i]);
1320         cp += sprintf(cp, "]:");
1321         return cp - rp;
1322 }
1323
1324 const char *FFOptions_Opt::unit_name(int id)
1325 {
1326         if( !opt || !opt->unit ) return 0;
1327         const void *obj = options->obj;
1328         if( !obj ) return 0;
1329
1330         const char *ret = 0;
1331         const AVOption *opt = NULL;
1332         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1333                 if( !opt->unit ) continue;
1334                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1335                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1336                 if( opt->default_val.i64 != id ) continue;
1337                 if( !ret ) { ret = opt->name;  continue; }
1338                 if( strlen(ret) < strlen(opt->name) ) ret = opt->name;
1339         }
1340
1341         return ret;
1342 }
1343
1344 const char *FFOptions_Opt::tip()
1345 {
1346         return !opt ? 0 : opt->help;
1347 }
1348
1349
1350 FFOptionsWindow::FFOptionsWindow(FFOptionsDialog *dialog)
1351  : BC_Window(_(PROGRAM_NAME ": Options"), 60, 30, 640, 400)
1352 {
1353         this->dialog = dialog;
1354         this->selected = 0;
1355 }
1356
1357 FFOptionsWindow::~FFOptionsWindow()
1358 {
1359 }
1360
1361 void FFOptionsWindow::create_objects()
1362 {
1363         BC_Title *title;
1364         int x0 = 10, y0 = 10;
1365         int x = x0, y = y0;
1366         add_subwindow(title = new BC_Title(x, y, _("Format: ")));
1367         x += title->get_w();
1368         add_subwindow(new BC_Title(x, y, dialog->format_name));
1369         x = x0 + 150;
1370         add_subwindow(title = new BC_Title(x, y, _("Codec: ")));
1371         x += title->get_w();
1372         add_subwindow(new BC_Title(x, y, dialog->codec_name));
1373
1374         x = x0;  y += title->get_h() + 10;  y0 = y;
1375         add_subwindow(title = new BC_Title(x, y, _("Type: ")));
1376         x += title->get_w() + 8;
1377         add_subwindow(type = new BC_Title(x, y, (char *)""));
1378         x = x0 + 150;
1379         add_subwindow(title = new BC_Title(x, y, _("Range: ")));
1380         x += title->get_w() + 8;
1381         add_subwindow(range = new BC_Title(x, y, (char *)""));
1382
1383         x = x0;  y += title->get_h() + 10;
1384         add_subwindow(units = new FFOptionsUnits(this, x, y, 120));
1385         x += units->get_w() + 8;
1386         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
1387         add_subwindow(text = new FFOptionsText(this, x, y, x1-x - 8));
1388         add_subwindow(apply = new FFOptionsApply(this, x1, y));
1389         y += units->get_h() + 10;
1390         add_subwindow(kind = new FFOptionsKind(this, x1, y0, apply->get_w()));
1391         kind->create_objects();
1392         const char *kind_text = _("Kind:");
1393         x1 -= BC_Title::calculate_w(this, kind_text) + 8;
1394         add_subwindow(kind_title = new BC_Title(x1, y0, kind_text));
1395         y0 = y;
1396
1397         panel_x = x0;  panel_y = y0;
1398         panel_w = get_w()-10 - panel_x;
1399         panel_h = get_h()-10 - panel_y - BC_OKButton::calculate_h();
1400         panel = new FFOptions_OptPanel(this, panel_x, panel_y, panel_w, panel_h);
1401         add_subwindow(panel);
1402         add_subwindow(new BC_OKButton(this));
1403         add_subwindow(new BC_CancelButton(this));
1404         panel->create_objects();
1405         options.initialize(this, FF_KIND_CODEC);
1406         draw();
1407         show_window(1);
1408 }
1409
1410 void FFOptionsWindow::draw()
1411 {
1412         update(selected);
1413 }
1414
1415 int FFOptionsWindow::resize_event(int w, int h)
1416 {
1417         int x1 = w - 8 - kind->get_w();
1418         int y = kind->get_y();
1419         kind->reposition_window(x1, y);
1420         x1 -= kind_title->get_w() + 8;
1421         kind_title->reposition_window(x1,y);
1422         x1 = get_w() - apply->get_w() - 8;
1423         int y1 = units->get_y();
1424         apply->reposition_window(x1, y1);
1425         int x0 = units->get_x() + units->get_w() + 8;
1426         int y0 = units->get_y();
1427         text->reposition_window(x0,y0, x1-x0-8);
1428         panel_w = get_w()-10 - panel_x;
1429         panel_h = get_h()-10 - panel_y;
1430         panel->reposition_window(panel_x,panel_y, panel_w, panel_h);
1431         return 1;
1432 }
1433
1434 FFOptionsDialog::FFOptionsDialog()
1435  : BC_DialogThread()
1436 {
1437         this->options_window = 0;
1438         this->codec_name = 0;
1439         this->codec = 0;
1440         this->ff_opts = 0;
1441         this->ff_len = 0;
1442 }
1443
1444 FFOptionsDialog::~FFOptionsDialog()
1445 {
1446         close_window();
1447         delete [] codec_name;
1448 }
1449
1450 void FFOptionsDialog::load_options(const char *bp, int len)
1451 {
1452         char line[BCTEXTLEN];
1453         char key[BCSTRLEN], val[BCTEXTLEN];
1454         const char *dp = bp + len-1;
1455         int no = 0;
1456         while( bp < dp && *bp != 0 ) {
1457                 ++no;
1458                 char *cp = line, *ep = cp+sizeof(line)-1;
1459                 while( *bp && cp<ep && (*cp=*bp++)!='\n' ) ++cp;
1460                 *cp = 0;
1461                 if( line[0] == '#' ) {
1462                         sprintf(key,"#%d", no);
1463                         av_dict_set(&ff_opts, key, line, 0);
1464                         continue;
1465                 }
1466                 if( line[0] == '\n' ) continue;
1467                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1468                 av_dict_set(&ff_opts, key, val, 0);
1469         }
1470 }
1471
1472 void FFOptionsDialog::store_options(char *cp, int len)
1473 {
1474         char *ep = cp + len-1;
1475         AVDictionaryEntry *elem = 0;
1476         while( (elem=av_dict_get(ff_opts, "", elem, AV_DICT_IGNORE_SUFFIX)) != 0 ) {
1477                 if( elem->key[0] == '#' ) {
1478                         cp += snprintf(cp,ep-cp, "%s\n", elem->value);
1479                         continue;
1480                 }
1481                 cp += snprintf(cp,ep-cp, "%s=%s\n", elem->key, elem->value);
1482         }
1483         *cp = 0;
1484 }
1485
1486 void FFOptionsDialog::start(const char *format_name, const char *codec_name,
1487         AVCodec *codec, const char *options, int len)
1488 {
1489         if( options_window ) {
1490                 options_window->lock_window("FFOptionsDialog::start");
1491                 options_window->raise_window();
1492                 options_window->unlock_window();
1493                 return;
1494         }
1495
1496         this->format_name = cstrdup(format_name);
1497         this->codec_name = cstrdup(codec_name);
1498         this->codec = codec;
1499         this->ff_opts = 0;
1500         this->ff_len = len;
1501         load_options(options, len);
1502
1503         BC_DialogThread::start();
1504 }
1505
1506 BC_Window* FFOptionsDialog::new_gui()
1507 {
1508         options_window = new FFOptionsWindow(this);
1509         options_window->create_objects();
1510         return options_window;
1511 }
1512
1513 void FFOptionsDialog::handle_done_event(int result)
1514 {
1515         if( !result ) {
1516                 char options[ff_len];
1517                 store_options(options, ff_len);
1518                 update_options(options);
1519         }
1520         options_window = 0;
1521         delete [] format_name; format_name = 0;
1522         delete [] codec_name;  codec_name = 0;
1523         av_dict_free(&ff_opts);
1524 }
1525
1526 FFOptionsAudioDialog::FFOptionsAudioDialog(FFMPEGConfigAudio *aud_config)
1527 {
1528         this->aud_config = aud_config;
1529 }
1530
1531 FFOptionsAudioDialog::~FFOptionsAudioDialog()
1532 {
1533         close_window();
1534 }
1535
1536 void FFOptionsAudioDialog::update_options(const char *options)
1537 {
1538         aud_config->audio_options->update(options);
1539 }
1540
1541 FFOptionsVideoDialog::FFOptionsVideoDialog(FFMPEGConfigVideo *vid_config)
1542 {
1543         this->vid_config = vid_config;
1544 }
1545
1546 FFOptionsVideoDialog::~FFOptionsVideoDialog()
1547 {
1548         close_window();
1549 }
1550
1551 void FFOptionsVideoDialog::update_options(const char *options)
1552 {
1553         vid_config->video_options->update(options);
1554 }
1555
1556
1557 FFOptionsViewAudio::FFOptionsViewAudio(FFMPEGConfigAudio *aud_config, int x, int y, const char *text)
1558  : BC_GenericButton(x, y, text)
1559 {
1560         this->aud_config = aud_config;
1561 }
1562
1563 FFOptionsViewAudio::~FFOptionsViewAudio()
1564 {
1565 }
1566
1567 int FFOptionsViewAudio::handle_event()
1568 {
1569         char audio_format[BCSTRLEN]; audio_format[0] = 0;
1570         char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1571         AVCodec *codec = 0;
1572         Asset *asset = aud_config->asset;
1573         const char *name = asset->acodec;
1574         if( !FFMPEG::get_format(audio_format, "audio", name) &&
1575             !FFMPEG::get_codec(audio_codec, "audio", name) )
1576                 codec = avcodec_find_encoder_by_name(audio_codec);
1577         if( !codec ) {
1578                 eprintf(_("no codec named: %s: %s"), name, audio_codec);
1579                 return 1;
1580         }
1581         aud_config->ff_options_dialog->start(audio_format, audio_codec, codec,
1582                 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1583         return 1;
1584 }
1585
1586 FFOptionsViewVideo::FFOptionsViewVideo(FFMPEGConfigVideo *vid_config, int x, int y, const char *text)
1587  : BC_GenericButton(x, y, text)
1588 {
1589         this->vid_config = vid_config;
1590 }
1591
1592 FFOptionsViewVideo::~FFOptionsViewVideo()
1593 {
1594 }
1595
1596 int FFOptionsViewVideo::handle_event()
1597 {
1598         char video_format[BCSTRLEN]; video_format[0] = 0;
1599         char video_codec[BCSTRLEN]; video_codec[0] = 0;
1600         AVCodec *codec = 0;
1601         Asset *asset = vid_config->asset;
1602         const char *name = asset->vcodec;
1603         if( !FFMPEG::get_format(video_format, "video", name) &&
1604             !FFMPEG::get_codec(video_codec, "video", name) )
1605                 codec = avcodec_find_encoder_by_name(video_codec);
1606         if( !codec ) {
1607                 eprintf(_("no codec named: %s: %s"), name, video_codec);
1608                 return 1;
1609         }
1610         vid_config->ff_options_dialog->start(video_format, video_codec, codec,
1611                 asset->ff_video_options, sizeof(asset->ff_video_options));
1612         return 1;
1613 }
1614