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