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