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