aboutsummaryrefslogtreecommitdiff
path: root/video.module
blob: d16a38b7d2921cfd27bab47de1416c818663d1ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
<?php

//$Id$
/**
 *
 * @file video.module
 *
 */
// include the field element
module_load_include('inc', 'video', 'video.field');

/*
 * Implementation of hook_init().
 */

function video_init() {
  drupal_add_css(drupal_get_path('module', 'video') . '/css/video.css');
  drupal_add_js(drupal_get_path('module', 'video') . '/js/video.js');
}

/**
 * Invokes hook_video_*action*() in every module.
 * Eg :
 * hook_video_submit()
 * hook_video_insert()
 * hook_video_preview()
 * hook_video_delete()
 * hook_video_load()
 * hook_video_form() - to show values once upload is completed eg. Resolution, and Convert on Save etc
 *
 * We cannot use module_invoke() for this, because the arguments need to
 * be passed by reference.
 */
function video_module_invoke($action, &$array, &$video = NULL, $other = NULL) {
  foreach (module_list () as $module) {
    $function = $module . '_video_' . $action;
    if (function_exists($function)) {
      $function($array, $video, $other);
    }
  }
}

/**
 * Implementation of hook_perm().
 */
function video_perm() {
  return array('bypass conversion video', 'convert on submission', 'override player dimensions', 'use default thumb');
}

/**
 * Implementation of hook_menu().
 */
function video_menu() {
  $items = array();
  $items['admin/config/media/video'] = array(
    'title' => 'Video',
    'description' => 'Configure different aspects of the video module and its plugins',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_general_admin_settings'),
    'file' => 'video.admin.inc',
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/media/video/general'] = array(
    'title' => 'General',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
  );
  $items['admin/config/media/video/players'] = array(
    'title' => 'Players',
    'description' => 'Configure your player settings for each video extension.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_players_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
  $items['admin/config/media/video/transcoders'] = array(
    'title' => 'Transcoders',
    'description' => 'Configure your transcoder to convert your videos or extra thumbnails.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_transcoder_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
  );
  $items['admin/config/media/video/presets'] = array(
    'title' => 'Presets',
    'description' => 'Configure your transcoder presets to convert your videos.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_preset_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 3,
  );
  $items['admin/config/media/video/metadata'] = array(
    'title' => 'Metadata',
    'description' => 'Configure your metadata settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_metadata_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 4,
  );

  $items['admin/config/media/video/filesystem'] = array(
    'title' => 'Filesystem',
    'description' => 'Configure your filesystem settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_filesystem_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
  );

  $items['admin/config/media/video/cron'] = array(
    'title' => 'Cron Settings',
    'description' => 'Configure your cron settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_cron_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'video.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 6,
  );


  return $items;
}

/**
 * Implementation of hook_theme().
 */
function video_theme() {
  $theme = array();
  $theme['video_thumbnails'] = array(
    'arguments' => array('file' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
    'file' => 'video.theme.inc',
  );
  $theme['video_widget'] = array(
    'render element' => 'element',
    'file' => 'video.theme.inc',
  );
  $theme['video_widget_preview'] = array(
    'arguments' => array('item' => TRUE),
    'file' => 'video.theme.inc',
  );
  $theme['video_image'] = array(
    'arguments' => array('file' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE, 'imagecache' => NULL),
    'file' => 'video.theme.inc',
  );
  $theme['video_widget_video_thumb'] = array(
    'arguments' => array('item' => TRUE),
    'file' => 'video.theme.inc',
  );
  $theme['video_formatter_video_plain'] = array(
    'arguments' => array('element' => NULL),
    'file' => 'video_formatter.inc',
  );
  $theme['video_formatter_video_nodelink'] = array(
    'arguments' => array('element' => NULL, 'imagecache' => NULL),
    'file' => 'video_formatter.inc',
  );
  //$theme['video_formatter_video_colorbox'] = array(
  //  'arguments' => array('element' => NULL, 'imagecache' => NULL),
  //  'file' => 'video_formatter.inc',
  //);
  $theme['video_formatter_video_media_js'] = array(
    'arguments' => array('element' => NULL),
    'file' => 'video_formatter.inc',
  );
  $theme['video_encoding_failed'] = array(
    'arguments' => array(),
    'file' => 'video_formatter.inc',
  );
  $theme['video_inprogress'] = array(
    'arguments' => array(),
    'file' => 'video_formatter.inc',
  );

  $path = drupal_get_path('module', 'video') . '/theme';
  //Lets setup our themes for our players
  $players = video_video_players();
  foreach ($players as $tpl => $value) {
    $theme[$tpl] = array(
      'arguments' => array('video' => NULL, 'node' => NULL, 'themed_output' => NULL),
      //#843368 fix
//      'file' => 'video_formatter.inc',
      'template' => str_replace('_', '-', $tpl),
      'path' => $path,
    );
  }
  //We need to add an flv theme buffer to allow users to override in their own module to add in extra parameters before
  //calling our flv template file.
  $theme['video_flv'] = array(
    'arguments' => array('video' => NULL, 'node' => NULL),
    'file' => 'video_formatter.inc'
  );

  //setup our imagecache presets
  if (module_exists('imagecache')) {
    //we need formatters for each of our thumbnails.
    //@todo create a function to check for our colorbox module and only add theme elements that could be used.
    $thumb_types = array('video_nodelink'); //array('video_colorbox', 'video_nodelink');
    foreach ($thumb_types as $types) {
      foreach (imagecache_presets () as $preset) {
        $theme['video_formatter_' . $preset['presetname'] . '__' . $types] = array(
          'arguments' => array('element' => NULL),
          'function' => 'theme_video_formatter_imagecache',
          'file' => 'video_formatter.inc'
        );
      }
    }
  }
  return $theme;
}

/*
 * Implmentation of hook_cron().
 */

function video_cron() {
  if (variable_get('video_cron', TRUE)) {
    module_load_include('inc', 'video', '/includes/conversion');
    $video_conversion = new video_conversion;
    $video_conversion->run_queue();
  }
}

/**
 * Implementation of hook_form_alter()
 * @param string $form
 * @param <type> $form_state
 * @param <type> $form_id 
 */
function video_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    $form['buttons']['submit']['#submit'][] = 'video_node_update_submit';
  }
}

function video_node_update_submit($form, &$form_state) {
  //lets update our video rending table to include the node id created
  if (isset($form_state['nid']) && isset($form_state['values']['video_id']) && is_array($form_state['values']['video_id'])) {
    foreach ($form_state['values']['video_id'] as $fid) {
      // @TODO : check for enable trancoder
      module_load_include('inc', 'video', '/includes/transcoder');
      $transcoder = new video_transcoder;
      $video = array('nid' => $form_state['nid'], 'fid' => $fid);
      $transcoder->update_job($video);
      // Lets other module to know to update
      video_module_invoke('update', $form, $form_state);
    }
  }
}

/*
 * Utility function that will add a preview of thumbnails for you to select when uploading videos.
 */

function video_thumb_process(&$element, &$form_state) {
  // Developed for ffmpeg support
  $file = $element['#value'];
  $delta = $file['fid'];
  $field = field_widget_field($element, $form_state);
  $instance = field_widget_instance($element, $form_state);
  $settings = $instance['widget']['settings'];
  $gen_fail = FALSE;

  if (isset($element['preview']) && $file['fid'] != 0) {
    $default_thumb = '';
    if (in_array($field['settings']['autothumbnail'], array('auto', 'auto_fallback'))) {

      module_load_include('inc', 'video', '/includes/transcoder');
      $transcoder = new video_transcoder;
      if ($thumbs = $transcoder->generate_thumbnails($file)) {
        $rnd_img = rand(0, variable_get('video_thumbs', 5) - 1);
        $default_thumb = $thumbs[$rnd_img]->uri;

        if (is_array($thumbs)) {
          foreach ($thumbs as $fid => $img) {
            // if file object contain url then use file name to identify object
            $key = $img->uri;
            $thumbss[$key] = theme('image_style', array('style_name' => $field['settings']['preview_video_thumb_style'], 'path' => $img->uri));
          }
        }
      }

      if (!empty($thumbss)) {
        $element['video_thumb'] = array(
          '#type' => 'radios',
          '#title' => t('Video Thumbnails'),
          '#options' => $thumbss,
          '#default_value' => !empty($file['video_thumb']) ? $file['video_thumb'] : $default_thumb,
          '#weight' => 10,
          '#attributes' => array('class' => array('video-thumbnails'), 'onchange' => 'videoftp_thumbnail_change()', 'rel' => 'video_large_thumbnail-' . $delta),
        );
      } else {
        $gen_fail = TRUE;
      }
    }

    if ((!empty($gen_fail) && $field['settings']['autothumbnail'] == 'auto_fallback') ||
        $field['settings']['autothumbnail'] == 'manual_upload') {

      $element['video_thumb_file'] = array(
        '#name' => 'files[' . $element['#field_name'] . '_' . $element['#delta'] . '_thumbs]',
        '#type' => 'file',
        '#size' => '40',
        '#title' => !empty($file['video_thumb']) ? t('Replace the video thumbnail') : t('Upload a video thumbnail'),
        '#description' => t('This thumbnail will be uploaded when the node is saved.'),
      );

      $element['video_thumb'] = array(
        '#type' => 'value',
        '#value' => isset($file['video_thumb']) ? $file['video_thumb'] : false,
      );
    }

    // Setup our large thumbnail that is on the left.
    // @todo Add smaller video preview instead of thumbnail?
    if (isset($file['video_thumb']) && !empty($file['video_thumb'])) {
      $large_thumb = array('filepath' => $file['video_thumb']);
    } elseif (!empty($field['settings']['default_video_thumb'])) {
      $large_thumb = $field['settings']['default_video_thumb'];
    } else {
      $large_thumb = array('filepath' => $default_thumb);
    }
//    print_r($field['settings']['default_video_thumbnail']);
    $default_thumbnail = file_load($field['settings']['default_video_thumbnail']);
    // @todo Integrate the thumbnails with imagecache.
    $element['preview']['#suffix'] = '<div class="video_large_thumbnail-' . $delta . '">' . theme('image_style', array('style_name' => $field['settings']['preview_video_thumb_style'], 'path' => $default_thumbnail->uri)) . '</div>';
  }
}

/**
 * Adds a video to the video rendering table.
 *
 * If auto converting, it will convert your video to flv right now.  We are passing the element by reference
 * just in case we ever want to add more to the element during this process.
 *
 * @param $element
 *   Form element to get the video file from.
 */
function video_convert_process(&$element) {
  $file = $element['#value'];
  // Add default dimensions from our default_value if needed
  if (!isset($file['data']['dimensions'])) {
    $file['data']['dimensions'] = $element['data']['dimensions']['#value'];
  }
  $convert = false;
  //we need to check if this fid has already been added to the database AND that there is in fact a fid
  if (is_array($file) && isset($file['fid']) && !empty($file['fid']) && !isset($file['data']['bypass_autoconversion'])) {
    $fid = $file['fid'];
    //setup our conversion class and check for the fid existence.
    module_load_include('inc', 'video', '/includes/conversion');
    $video_conversion = new video_conversion;

    // Lets verify that we haven't added this video already.  Multiple validation fails will cause this to be ran more than once
    if (!$video = $video_conversion->load_job($fid)) {
      // Video has not been added to the queue yet so lets add it.
      $video = array('fid' => $fid, 'dimensions' => $file['data']['dimensions']);
      if (!($video_conversion->create_job($video)))
        drupal_set_message(t('Something went wrong with your video job creation.  Please check your recent log entries for further debugging.'), 'error');
      $convert = true;
      //lets queue our node status to unpublished.
      $element['#unpublish'] = true;
    } elseif ($video->video_status != VIDEO_RENDERING_COMPLETE) {
      //lets queue our node status to unpublished.
      $element['#unpublish'] = true;
    }

    // Our video should be in the database pending, lets see if we need to convert it now.
    // Check if we are going from unselected to selected or if this is a new video and we have checked the checkbox
    $convert_video_on_save = false;
    $element_data_convert_on_save = '';
    $file_date_convet_on_save = '';
    $convert_on_save = variable_get('video_convert_on_save', FALSE);
    if (isset($element['data']['convert_video_on_save']['#value']))
      $element_data_convert_on_save = $element['data']['convert_video_on_save']['#value'];
    if (isset($file['data']['convert_video_on_save']))
      $file_date_convet_on_save = $file['data']['convert_video_on_save'];
    $convert_video_on_save = $element_data_convert_on_save || $file_date_convet_on_save;
    if (((!isset($element['#default_value']['data']['convert_video_on_save']) || !$element['#default_value']['data']['convert_video_on_save'])
        && $convert_video_on_save) || ($convert && $convert_video_on_save) || $convert_on_save) {
      $return = $video_conversion->process($fid);
      if ($return === FALSE) {
        drupal_set_message(t('Something went wrong with your video conversion.  Please check your recent log entries for further debugging.'), 'error');
      } elseif ($return === TRUE) {
        //we are always unpublished until we are converted.
        unset($element['#unpublish']);
        drupal_set_message(t('Successfully converted your video.'));
      }
    } elseif ($convert) {
      drupal_set_message(t('Video submission queued for processing. Please wait: our servers are preparing your video for display.'));
    }
  }
}

/**
 * Implementation of hook_file_delete().
 */
function video_file_delete($file) {
  // @TODO : check for enable trancoder
  // delete the transcoder job
  module_load_include('inc', 'video', '/includes/transcoder');
  $transcoder = new video_transcoder;
  $transcoder->delete_job($file);

  //now lets delete our video thumbnails and folder.
  $video_thumb_path = variable_get('video_thumb_path', 'video_thumbs');
  $thumb_folder = file_default_scheme() . ':/' . $video_thumb_path . '/' . $file->fid;
  // Recursively delete our folder and files
  rmdirr($thumb_folder);
  // Let other modules to know about the file delete
  video_module_invoke('delete', $file);
}

/**
 * Compares passed extensions with normal video web extensions.
 */
function video_web_extensions($ext) {
  $extensions = array_filter(explode(' ', $ext));
  $web_extensions = array(
    'mov', 'mp4', '3gp', '3g2', 'mpg', 'mpeg', // quicktime
    'divx', //divx
    'rm', // realplayer
    'flv', 'f4v', //flash player
    'swf', // swf player
    'dir', 'dcr', // dcr player
    'asf', 'wmv', 'avi', 'mpg', 'mpeg', // windows media
    'ogg', 'ogv', 'webm' // ogg/ogv theora
  );
  if (count(array_diff($extensions, $web_extensions))) {
    return FALSE;
  }
  return TRUE;
}

/**
 * Implementation of hook_views_api().
 */
function video_views_api() {
  return array(
    'api' => 2.0,
    'path' => drupal_get_path('module', 'video') . '/views',
  );
}

/**
 * Process elements loads on settings
 * @param <type> $element
 */
function video_widget_element_settings(&$element, &$form_state) {
  $file = $element['#value'];
  $delta = $element['#delta'];

  $field = field_widget_field($element, $form_state);
  $instance = field_widget_instance($element, $form_state);
  $settings = $instance['settings'];
  // Check if using the default width and replace tokens.
  $default_dimensions = user_access('override player dimensions');
  $description = t('Set your video dimensions.  This will create your player with these dimensions.');
  //setup our default dimensions.
  $dimensions = $settings['default_dimensions'];
  $player_dimensions = $settings['default_player_dimensions'];
  // Lets figure out our dimensions for our video and add astericks next to our options.
  $options = video_explode("\n", variable_get("video_metadata_dimensions", video_default_dimensions()));
  if ($field['settings']['autoconversion'] && isset($element['preview']) &&
      $file['fid'] != 0 && $default_dimensions) {
    $file_object = file_load($file['fid']);
    $video_info = _video_dimensions_options($options, drupal_realpath($file_object->uri));
    $description = t('Set your video dimensions.  This will create your player
      and transcode your video with these dimensions.  Your video size is !size,
      if you choose a higher resolution, this could cause video distortion.
      You are shown dimensions that match your aspect ratio,
      if you choose dimensions that do not match your ratio, we will pad your
      video by adding black bars on either the top or bottom while maintaining
      your videos original aspect ratio.',
            array('!size' => $video_info['width'] . 'x' . $video_info['height']));
    //setup our default display of dimensions.
    //lets go through our options looking for a matching resolution
    foreach ($options as $key => $value) {
      if (stristr($value, t('(Matches Resolution)')) == TRUE) {
        $dimensions = $key;
        break;
      }
    }
  }
  // Override our dimensions to the user selected.
  if (isset($file['dimensions']) && !empty($file['dimensions'])) {
    $dimensions = $file['data']['dimensions'];
  }

  // Override our player dimensions to the user selected.
  if (isset($file['player_dimensions']) && !empty($file['player_dimensions'])) {
    $player_dimensions = $file['player_dimensions'];
  }

  // show only enabled the autoconversion
  if ($field['settings']['autoconversion']) {
    $element['dimensions'] = array(
      '#type' => 'select',
      '#title' => t('Dimensions for Video Transcoding'),
      '#default_value' => $dimensions,
      '#description' => $description,
      '#options' => $options,
    );
  }
  // get the player dimentions
  $element['player_dimensions'] = array(
    '#type' => 'select',
    '#title' => t('Dimensions for Video Player'),
    '#default_value' => $player_dimensions,
    '#description' => t('WxH of your video player.'),
    '#options' => $options,
  );
  // If users cannot change the default dimensions, lets change this to a value.
  if (!$default_dimensions) {
    $element['dimensions']['#type'] = 'value';
    $element['dimensions']['#value'] = $dimensions;
    $element['player_dimensions']['#type'] = 'value';
    $element['player_dimensions']['#value'] = $player_dimensions;
  }

  // only in preview mode and then create thumbnails
  if ($field['settings']['autoconversion']) {
    if (user_access('bypass conversion video')) {
      $element['bypass_autoconversion'] = array(
        '#type' => 'checkbox',
        '#title' => t('Bypass auto conversion'),
        '#default_value' => isset($file['bypass_autoconversion']) ? $file['bypass_autoconversion'] : variable_get('video_bypass_conversion', FALSE),
        '#description' => t('This will bypass your auto conversion of videos.'),
        '#attributes' => array('class' => array('video-bypass-auto-conversion')),
      );
    }
// check this to convert the video on save
    $convert = isset($file['convert_video_on_save']) ? $file['convert_video_on_save'] : variable_get('video_convert_on_save', FALSE);
    if (user_access('convert on submission')) {
      $element['convert_video_on_save'] = array(
        '#type' => 'checkbox',
        '#title' => t('Convert video on save'),
        '#default_value' => $convert,
        '#description' => t('This will convert your video to flv format when you save, instead of scheduling it for cron.'),
        '#attributes' => array('class' => array('video-convert-video-on-save')),
      );

      if ($convert) {
        $element['convert_video_on_save']['#attributes']['checked'] = 'checked';
      }
    } else {
      $element['convert_video_on_save'] = array(
        '#type' => 'value',
        '#value' => $convert,
      );
    }
  }

  // use of default thumbnail
  $default_thumb = isset($file['use_default_video_thumb']) ? $file['use_default_video_thumb'] : variable_get('video_use_default_thumb', FALSE);
  if (user_access('use default thumb')) {
    $element['use_default_video_thumb'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use the default thumbnail for this video?'),
      '#default_value' => $default_thumb,
      '#description' => t('This will set a flag for this video to use the default video thumbnail when outputed..'),
      '#attributes' => array('class' => array('video-use-default-video-thumb')),
    );
    if ($default_thumb) {
      $element['use_default_video_thumb']['#attributes']['checked'] = 'checked';
    }
  } else {
    $element['use_default_video_thumb'] = array(
      '#type' => 'value',
      '#value' => $default_thumb,
    );
  }
}

/**
 * Video_widget_process for API handlers for any video types.
 * @param <type> $element
 * @param <type> $form_state
 */
function video_widget_process(&$element, &$form_state) {
  $item = $element['#value'];
  $field = field_widget_field($element, $form_state);
  switch ($form_state['clicked_button']['#submit'][0]) {
    case 'node_form_submit':
      // Auto convert our video file
      if ($field['settings']['autoconversion']) {
        video_convert_process($element);
        //lets set our node status to unpublished if our video is not converted.
        if (isset($element['#unpublish']) && $element['#unpublish']) {
          //unpublish the node
          $form_state['values']['status'] = 0;
        }
      }

      // Save manually uploaded thumbs (if they exist) and add them to element
      if (isset($_FILES['files']) && is_array($_FILES['files']['name']))
        if (array_key_exists($field['field_name'] . '_' . $element['#delta'] . '_thumbs', $_FILES['files']['name'])) {
          video_upload_manual_thumb($element);
        }

      // Call hook_video_submit API
      video_module_invoke('insert', $element, $form_state);
      //
      //queue up the file id to update the node id in the video rendering / cdn tables.
      $form_state['values']['video_id'][] = $item['fid'];
      break;
    case 'node_form_build_preview':
      // Call hook_video_preview API
      video_module_invoke('preview', $element, $form_state);
      break;
    case 'node_form_delete_submit':
      //moved to hook_file_delete in video module.
      break;
  }
}

/**
 * Handle saving of manual thumbs
 */
function video_upload_manual_thumb(&$element) {

  $destination = file_default_scheme() . ':/' . 'video_thumbs/' . $element['#value']['fid'];
  if (!field_file_check_directory($destination, FILE_CREATE_DIRECTORY)) {
    form_set_error('video_thumb_upload', t('The thumbnail image could not be uploaded. The destination %destination does not exist or is not writable by the server.', array('%destination' => dirname($destination))));
    return;
  }
  $validators = array(
    'file_validate_is_image' => array(),
  );

  if (!$file = file_save_upload($element['#field_name'] . '_' . $element['#delta'] . '_thumbs', $validators, $destination)) {
    // No upload to save we hope... or file_save_upload() reported an error on its own.
    return;
  }

  // Remove old image (if any) & clean up database.
  $old_thumb = $element['data']['video_thumb']['#value'];
  if (!empty($old_thumb)) {
    if (file_delete($old_thumb)) {
      db_query('DELETE FROM {files} WHERE filepath=%d', $old_thumb);
    }
  }
  // Make the file permanent and store it in the form.
  file_set_status($file, FILE_STATUS_PERMANENT);
  $element['data']['video_thumb']['#value'] = $file->filepath;
}

/*
 * Function updates our options list to show matching aspect ratios and if we have a matching resolution.
 * 
 * We will update the options array by reference and return the aspect ratio of the file.
 */

function _video_dimensions_options(&$options, $video) {
  $aspect_ratio = _video_aspect_ratio($video);
  //loop through our options and find matching ratio's and also the exact width/height
  foreach ($options as $key => $value) {
    $wxh = explode('x', $value);
    //lets check our width and height first
    if ($aspect_ratio['width'] == $wxh[0] && $aspect_ratio['height'] == $wxh[1]) {
      $options[$key] = $value . ' ' . t('(Matches Resolution)');
    } else {
      //now lets check our ratio's
      $ratio = number_format($wxh[0] / $wxh[1], 4);
      if ($ratio == $aspect_ratio['ratio']) {
        $options[$key] = $value . ' ' . t('(Matches Ratio)');
      }
    }
  }
  return $aspect_ratio;
}

/*
 * Returns the width/height and aspect ratio of the video
 * 
 * @todo: move this to the transcoder class instead?
 */

function _video_aspect_ratio($video) {
  //lets get our video dimensions from the file
  module_load_include('inc', 'video', '/includes/transcoder');
  $transcoder = new video_transcoder;
  $wxh = $transcoder->get_dimensions($video);
  $width = $wxh['width'];
  $height = $wxh['height'];

  if (!$width || !$height) {
    //no width and height found just return.
    watchdog('video_conversion', 'We could not determine the height and width of the video: ' . $video, array(), WATCHDOG_DEBUG);
//    drupal_set_message(t('The system counld not determine the width and height of your video: !video.  If transcoding, the system could have problems.', array('!video' => $video)));
    return;
  }

  //now lets get aspect ratio and compare our options in the select dropdown then add an asterick if any to each option representing a matching aspect ratio.
  $ratio = number_format($width / $height, 4);
  $aspect_ratio = array(
    'width' => $width,
    'height' => $height,
    'ratio' => $ratio,
  );
  return $aspect_ratio;
}

/*
 * Return our list of video extensions and their associated player.
 */

function video_video_extensions() {
  $extensions = array(
    'divx' => 'video_play_divx',
    'mov' => 'video_play_quicktime',
    '3gp' => 'video_play_quicktime',
    '3g2' => 'video_play_quicktime',
    'mp4' => 'video_play_quicktime',
    'rm' => 'video_play_realmedia',
    'f4v' => 'video_play_flv',
    'flv' => 'video_play_flv',
    'swf' => 'video_play_flash',
    'dir' => 'video_play_dcr',
    'dcr' => 'video_play_dcr',
    'asf' => 'video_play_windowsmedia',
    'wmv' => 'video_play_windowsmedia',
    'avi' => 'video_play_windowsmedia',
    'mpg' => 'video_play_windowsmedia',
    'mpeg' => 'video_play_windowsmedia',
    'ogg' => 'video_play_theora',
    'ogv' => 'video_play_theora',
    'webm' => 'video_play_theora'
  );
  return $extensions;
}

/*
 * Return our supported video players.
 */

function video_video_players() {
  $players = array(
    'video_play_html5' => t('HTML5 Player'),
    'video_play_divx' => t('Divx Player'),
    'video_play_quicktime' => t('Quicktime'),
    'video_play_realmedia' => t('Real Media Player'),
    'video_play_flv' => t('FLV Flash Players'),
    'video_play_flash' => t('SWF Flash Player'),
    'video_play_dcr' => t('Director/Shockwave'),
    'video_play_windowsmedia' => t('Windows Media Player'),
    'video_play_theora' => t('Theora Player'),
  );
  return $players;
}

/*
 * Return our possible flash players.
 */

function video_video_flv_players() {
  $options = array();
  if (module_exists('swftools')) {
    $options['swftools'] = t('SWF Tools');
  }
  if (module_exists('flowplayer')) {
    $options['flowplayer'] = t('Flowplayer');
  }
  return $options;
}

/**
 * Get the object for the suitable player for the parameter resource
 */
function video_get_player($element) {
  // Setup our node object to be passed along with the player.
  $node = $element['#node'];
  // Setup our video object
  module_load_include('inc', 'video', '/includes/video_helper');
  $video_helper = new video_helper;
  $video = $video_helper->video_object($element);
  // Lets spit out our theme based on the extension
  $defaults = video_video_extensions();
  $theme_function = variable_get('video_extension_' . $video->player, $defaults[$video->player]);
  // Lets do some special handling for our flv files to accomdate multiple players.
  if ($theme_function == 'video_play_flv') {
    return theme('video_flv', $video, $node);
  } else {
    return theme($theme_function, $video, $node);
  }
}

function video_default_instance_settings($widget) {
  $form = array();
  // Default video settings.
  $form['default_dimensions'] = array(
    '#type' => 'select',
    '#title' => t('Default Video Resolution Dimensions'),
    '#default_value' => !empty($widget['default_dimensions']) ? $widget['default_dimensions'] : '',
    '#options' => video_explode("\n", variable_get("video_metadata_dimensions", video_default_dimensions())),
    '#description' => t('Default transcoding resolution WIDTHxHEIGHT, in px, that FFMPEG will use to transcode your video files.'),
    '#weight' => 15,
  );
  $form['default_player_dimensions'] = array(
    '#type' => 'select',
    '#title' => t('Default Video Player Dimensions'),
    '#default_value' => !empty($widget['default_player_dimensions']) ? $widget['default_player_dimensions'] : '',
    '#options' => video_explode("\n", variable_get("video_metadata_dimensions", video_default_dimensions())),
    '#description' => t('Default player WIDTHxHEIGHT in px.  This is your actual player dimensions that your video will be playing in.'),
    '#weight' => 16,
  );
  return $form;
}

function video_default_field_settings($settings) {
  $form = array();
  // Default video field settings.
  $form['autoconversion'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable video conversion.'),
    '#description' => t('Use ffmpeg(Default) or Zencoder to automatically convert videos to web compatible types eg. FLV, Please make sure to configure your transcoder settings.'),
    '#default_value' => isset($settings['autoconversion']) ? $settings['autoconversion'] : '',
    '#weight' => 17,
  );

  $thumb_options = array(
    'auto' => 'Automatically generate thumbnails',
    'auto_fallback' => 'Automatically generate thumbnails, with fallback to manual upload',
    'manual_upload' => 'Manually upload a thumbnail',
    'no' => 'Don\'t create thumbnail',
  );

  $form['autothumbnail'] = array(
    '#type' => 'radios',
    '#title' => t('Thumbnail Generation'),
    '#options' => $thumb_options,
    '#description' => t('To use ffmpeg(Default) to create thumbnails, Please make sure to configure your transcoder settings before using ffmpeg to create thumbnails.'),
    '#default_value' => isset($settings['autothumbnail']) ? $settings['autothumbnail'] : 'no',
    '#weight' => 18,
  );

  $form['default_video_thumbnail'] = array(
    '#title' => t('Default video thumbnail'),
    '#type' => 'managed_file',
//    '#element_validate' => array('video_field_default_thumbnail_validate'),
    '#description' => t('If use default thumbnanil is selected, this image will be shown on display.'),
    '#default_value' => !empty($settings['default_video_thumbnail']) ? $settings['default_video_thumbnail'] : '',
    '#upload_location' => 'public://videos/thumbnails/default',
    '#weight' => 19,
  );
  $form['preview_video_thumb_style'] = array(
    '#title' => t('Preview thumbnail style'),
    '#type' => 'select',
    '#options' => image_style_options(FALSE),
    '#empty_option' => '<' . t('no preview') . '>',
    '#default_value' => !empty($settings['preview_video_thumb_style']) ? $settings['preview_video_thumb_style'] : '',
    '#description' => t('The preview image will be shown while editing the content.'),
    '#weight' => 20,
  );
  return $form;
}

/*
 * #options helper function to set our key=value for the form api.
 */

function video_explode($delimeter, $dimensions) {
  $options = array();
  $values = explode($delimeter, $dimensions);
  foreach ($values as $value) {
    //lets check we have a value and its in the right format
    if (!empty($value) && video_format_right($value)) {
      $options[trim($value)] = trim($value);
    }
  }
  return $options;
}

function video_format_right($value) {
  $format = explode("x", $value);
  if (!isset($format[0]) || !is_numeric(trim($format[0])))
    return false;
  if (!isset($format[1]) || !is_numeric(trim($format[1])))
    return false;
  return true;
}

/*
 * Default video dimensions.
 */

function video_default_dimensions() {
  return "176x144\n352x288\n704x576\n1408x1152\n128x96\n160x120\n320x240\n640x480\n800x600\n1024x768\n1600x1200\n2048x1024\n1280x1024\n2560x2048\n5120x4096\n852x480\n1366x768\n1600x1024\n1920x1200\n2560x1600\n3200x2048\n3840x2400\n6400x4096\n7680x4800\n320x200\n640x350\n852x480\n1280x720\n1920x1080";
}

/*
 * Utility function to remove all files and directories recursively.
 */

function rmdirr($dir) {
  if ($objs = glob($dir . "/*")) {
    foreach ($objs as $obj) {
      is_dir($obj) ? rmdirr($obj) : unlink($obj);
    }
  }
  @rmdir($dir);
}