summaryrefslogtreecommitdiffstats
path: root/video.field.inc
blob: d6958da94af1ff304e93c08b738ff6a95cb95392 (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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
<?php
/**
 * @file
 * Implement a video field, based on the file module's file field.
 */

/**
 * Implements hook_field_info().
 */
function video_field_info() {
  return array(
    'video' => array(
      'label' => t('Video'),
      'description' => t('This field stores the ID of a video file as an integer value.'),
      'settings' => array(
        'uri_scheme' => variable_get('file_default_scheme', 'public'),
        'uri_scheme_converted' => variable_get('file_default_scheme', 'public'),
        'uri_scheme_thumbnails' => variable_get('file_default_scheme', 'public'),
        'thumbnail_format' => 'jpg',
        'autoconversion' => 1,
        'autothumbnail' => 'auto',
        'default_video_thumbnail' => 0,
        'preview_video_thumb_style' => 'thumbnail',
        'presets' => array(),
      ),
      'instance_settings' => array(
        'file_extensions' => 'mp4 ogg avi mov wmv flv ogv webm',
        'file_directory' => 'videos/original',
        'max_filesize' => '',
        'default_dimensions' => '640x360',
      ),
      'default_widget' => 'video_upload',
      'default_formatter' => 'video_formatter_player',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function video_field_settings_form($field, $instance, $has_data) {
  $transcoder = new Transcoder();
  $hastranscoder = $transcoder->hasTranscoder();

  $defaults = field_info_field_settings($field['type']);
  $settings = array_merge($defaults, $field['settings']);

  // Copied from file_field_settings_form().
  $scheme_options = array();
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
    $scheme_options[$scheme] = $stream_wrapper['name'];
  }
  $form['uri_scheme'] = array(
    '#type' => 'radios',
    '#title' => t('Upload destination of original file'),
    '#options' => $scheme_options,
    '#default_value' => $settings['uri_scheme'],
    '#description' => t('Select where the original video files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
  );
  $form['uri_scheme_converted'] = array(
    '#type' => 'radios',
    '#title' => t('Upload destination of converted files'),
    '#options' => $scheme_options,
    '#default_value' => $settings['uri_scheme_converted'],
    '#description' => t('Select where the converted video files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
    '#access' => $hastranscoder,
  );
  $form['uri_scheme_thumbnails'] = array(
    '#type' => 'radios',
    '#title' => t('Upload destination of thumbnails'),
    '#options' => $scheme_options,
    '#default_value' => $settings['uri_scheme_thumbnails'],
    '#description' => t('Select where the generated thumbnails should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
    '#access' => $hastranscoder,
  );

  // Add warnings for S3
  if ($hastranscoder && isset($scheme_options['s3'])) {
    $value = $transcoder->getTranscoder()->getValue();

    if ($value == 'TranscoderAbstractionFactoryFfmpeg') {
      $form['uri_scheme']['#description'] .= '<br/>';
      $form['uri_scheme']['#description'] .= t('You are using the FFmpeg transcoder. Using @scheme to store videos is not advised because FFmpeg is not able to transcode remote files. Every time FFmpeg needs access to the video, it will be copied to a temporary location.', array('@scheme' => $scheme_options['s3']));
    }

    $form['uri_scheme_thumbnails']['#description'] .= '<br/>';
    $form['uri_scheme_thumbnails']['#description'] .= t('Be aware that using @scheme to store thumbnails increases the overhead of dynamic image manipulation by the Image module.', array('@scheme' => $scheme_options['s3']));
  }

  // Add warnings for streaming to iPad when using the private file system
  // See http://www.metaltoad.com/blog/iphone-video-streaming-drupals-file-system
  if (isset($scheme_options['private']) && !module_exists('xsendfile') && !module_exists('resumable_download')) {
    $ioswarning = '<br/>' . t('Streaming to Apple iOS devices (iPad/iPhone/iPod) is not supported when using the private file system unless a module to support Range requests is installed. Modules that are known to work are <a href="@xsendfile-module">X-Sendfile</a> or <a href="@resumable-download-module">Resumable Download</a>.', array('@xsendfile-module' => url('http://drupal.org/project/xsendfile'), '@resumable-download-module' => url('http://drupal.org/project/resumable_download')));
    $form['uri_scheme']['#description'] .= $ioswarning;
    $form['uri_scheme_converted']['#description'] .= $ioswarning;
  }

  $form['autoconversion'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable auto video conversion'),
    '#description' => t('Convert videos automatically using FFmpeg or Zencoder. You can define presets at !preset to automatically convert videos to web compatible formats eg. FLV, MP4. Make sure to configure your !settings to make this work properly.', array(
      '!settings' => l(t('transcoder settings'), 'admin/config/media/video/transcoders'),
      '!preset' => l(t('preset settings'), 'admin/config/media/video/presets'),
    )),
    '#default_value' => isset($settings['autoconversion']) ? $settings['autoconversion'] : '',
    '#access' => $hastranscoder,
  );

  $form['thumbnail_format'] = array(
    '#title' => t('Thumbnail format'),
    '#type' => 'radios',
    '#options' => array('jpg' => 'JPEG', 'png' => 'PNG'),
    '#default_value' => !empty($settings['thumbnail_format']) ? $settings['thumbnail_format'] : 'jpg',
    '#access' => $hastranscoder,
  );

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

  // When there is no transcoder, the auto option is not available and should not be the default.
  if (!$hastranscoder) {
    unset($thumb_options['auto']);
    if (!isset($settings['autothumbnail']) || $settings['autothumbnail'] == 'auto') {
      $settings['autothumbnail'] = 'no';
    }
  }

  $form['autothumbnail'] = array(
    '#type' => 'radios',
    '#title' => t('Video thumbnails'),
    '#options' => $thumb_options,
    '#description' => t('If you choose <i>Automatically extract thumbnails from video</i> then please make sure to configure your !settings to make this work properly.', array('!settings' => l(t('transcoder settings'), 'admin/config/media/video/transcoders'))),
    '#default_value' => isset($settings['autothumbnail']) ? $settings['autothumbnail'] : 'auto',
  );

  $form['default_video_thumbnail'] = array(
    '#title' => t('Default video thumbnail'),
    '#type' => 'managed_file',
    '#element_validate' => array('video_field_default_thumbnail_validate'),
    '#description' => t('You can use a default thumbnail for all videos or videos from which a thumbnail can\'t be extracted. Settings to use default video thumbnails will be available on node edit. You can change the permissions for other users too.'),
    '#default_value' => !empty($settings['default_video_thumbnail']['fid']) ? $settings['default_video_thumbnail']['fid'] : '',
    '#upload_location' => 'public://videos/thumbnails/default',
  );

  $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('This image style will be used to show extracted video thumbnails on video node edit. Extracted thumbnail preview will also use this style.'),
  );

  $selectedpresets = array_filter(variable_get('video_preset', array()));
  $presets = Preset::getAllPresets();
  $presetnames = array();
  foreach ($presets as $preset) {
    $presetnames[$preset['name']] = $preset['name'];

    if (in_array($preset['name'], $selectedpresets)) {
      $presetnames[$preset['name']] .= ' (' . t('default') . ')';
    }
  }

  $form['presets'] = array(
    '#title' => t('Presets'),
    '#type' => 'checkboxes',
    '#options' => $presetnames,
    '#default_value' => !empty($settings['presets']) ? $settings['presets'] : array(),
    '#description' => t('If any presets are selected, these presets will be used for this field instead of the default presets.'),
    '#access' => $hastranscoder,
  );

  return $form;
}

/**
 * Element specific validation for video default value.
 */
function video_field_default_thumbnail_validate($element, &$form_state) {
  $settings = $form_state['values']['field']['settings'];
  // Make the file permanent and store it in the form.
  if (!empty($settings['default_video_thumbnail']['fid'])) {
    $file = file_load($settings['default_video_thumbnail']['fid']);
    $file->status = FILE_STATUS_PERMANENT;
    $file = file_save($file);
    $form_state['values']['field']['settings']['default_video_thumbnail'] = (array) $file;
  }
}

/**
 * Implements hook_field_instance_settings_form().
 */
function video_field_instance_settings_form(array $field, array $instance) {
  $widget = $instance['settings'];

  // Use the file field instance settings form as a basis.
  $form = file_field_instance_settings_form($field, $instance);

  // Remove the description option.
  unset($form['description_field']);

  $form['default_dimensions'] = array(
    '#type' => 'select',
    '#title' => t('Output video dimensions'),
    '#default_value' => !empty($widget['default_dimensions']) ? $widget['default_dimensions'] : '',
    '#options' => video_utility::getDimensions(),
    '#description' => t('This setting can be overridden in node edit or preset settings. Select the most suitable values to use as output dimensions, as selecting a bad value could cause video conversion to fail.'),
    '#weight' => 16,
  );

  return $form;
}

/**
 * Implements hook_field_load().
 */
function video_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);

  // Load all files we need for these entities
  $videofids = array();
  $fids = array();
  foreach ($entities as $id => $entity) {
    // Load the files from the files table.
    foreach ($items[$id] as $delta => $item) {
      if (empty($item) || empty($item['fid'])) {
        continue;
      }
      $videofids[] = $item['fid'];
      if (!empty($item['thumbnail'])) {
        $fids[] = $item['thumbnail'];
      }
    }
  }

  if (empty($videofids)) {
    return;
  }

  // Load the queues
  $queues = db_select('video_queue', 'q')
    ->fields('q')
    ->condition('q.fid', $videofids, 'IN')->execute()->fetchAllAssoc('fid');

  // Load the derived files
  $outputs = db_select('video_output', 'vo')
    ->fields('vo')
    ->condition('vo.original_fid', $videofids, 'IN')
    ->execute()->fetchAllAssoc('output_fid');

  $fids = array_merge($fids, array_keys($outputs));
  $files = file_load_multiple($fids);

  // Apply the found information to all files for all entities
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {
      if (empty($item) || empty($item['fid'])) {
        continue;
      }
      // Check whether transcoding is enabled for this file
      if (isset($queues[$item['fid']])) {
        $items[$id][$delta]['autoconversion'] = TRUE;
        $items[$id][$delta]['conversioncompleted'] = $queues[$item['fid']]->status == VIDEO_RENDERING_COMPLETE;
        $items[$id][$delta]['conversionstatus'] = $queues[$item['fid']]->status;

        // Load converted files
        $items[$id][$delta]['playablefiles'] = array();
        foreach ($outputs as $outputfid => $output) {
          if ($output->original_fid == $items[$id][$delta]['fid'] && isset($files[$outputfid]) && $files[$outputfid]->filesize > 0) {
            $conv = (array)$files[$outputfid] + (array)$output;
            $items[$id][$delta]['playablefiles'][] = (object)$conv;
          }
        }

        // If for some reason there are no playable files, mark the status as failed
        if (empty($items[$id][$delta]['playablefiles']) && $items[$id][$delta]['conversioncompleted']) {
          $items[$id][$delta]['conversioncompleted'] = FALSE;
          $items[$id][$delta]['conversionstatus'] = VIDEO_RENDERING_FAILED;
        }
      }
      else {
        $items[$id][$delta]['playablefiles'] = array((object)$items[$id][$delta]);
        $items[$id][$delta]['autoconversion'] = FALSE;
      }

      // Load thumbnail
      if (empty($item['thumbnail']) || !isset($files[$item['thumbnail']])) {
        $items[$id][$delta]['thumbnail'] = NULL;
        $items[$id][$delta]['thumbnailfile'] = NULL;
      }
      else {
        $items[$id][$delta]['thumbnailfile'] = $files[$item['thumbnail']];
      }
    }
  }
}

/**
 * Implements hook_field_validate().
 *
 * This allows field validation even when the file is added programmatically to
 * the entity. The function only validates new files, not files that have been
 * added to the entity before.
 */
function video_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  $current_fids = array();

  // Get the video fids
  foreach ($items as $delta => $item) {
    if (empty($item['fid'])) {
      continue;
    }
    $current_fids[$item['fid']] = $item['fid'];
  }

  if (empty($current_fids)) {
    return;
  }

  // Create a bare-bones entity so that we can load its previous values.
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
  field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT, array('field_id' => $field['id']));

  // Remove the entries from $current_fids that are already present in the database,
  // leaving the ones that are new during this save operation.
  if (!empty($original->{$field['field_name']}[$langcode])) {
    foreach ($original->{$field['field_name']}[$langcode] as $originalitem) {
      if (isset($originalitem['fid']) && isset($current_fids[$originalitem['fid']])) {
        unset($current_fids[$originalitem['fid']]);
      }
    }
  }

  if (empty($current_fids)) {
    // No new files have been added, only new files are checked
    return;
  }

  $current_files = file_load_multiple($current_fids);
  $validators = file_field_widget_upload_validators($field, $instance);
  if (empty($validators)) {
    // No validation rules
    return;
  }

  // Validate the new entries
  foreach ($items as $delta => $item) {
    if (empty($item['fid']) || !isset($current_files[$item['fid']])) {
      continue;
    }

    $fileerrors = file_validate($current_files[$item['fid']], $validators);

    foreach ($fileerrors as $fileerror) {
      $errors[$field['field_name']][$langcode][$delta][] = array(
        'error' => 'video_upload',
        'message' => $fileerror,
      );
    }
  }
}

/**
 * Implements hook_field_widget_error().
 *
 * Work-around for Drupal bug http://drupal.org/node/1432732
 */
function video_field_widget_error($element, $error, $form, &$form_state) {
  form_error($element, $error['message']);
}

/**
 * Implements hook_field_presave().
 */
function video_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // change the thumbnails if default is checked
  foreach ($items as $delta => $item) {
    if (!empty($field['settings']['default_video_thumbnail']['fid'])) {
      if (!empty($item['use_default_video_thumb'])) {
        $items[$delta]['thumbnail'] = $field['settings']['default_video_thumbnail']['fid'];
      }
    }
  }

  file_field_presave($entity_type, $entity, $field, $instance, $langcode, $items);
}

/**
 * Implements hook_field_insert().
 */
function video_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  file_field_insert($entity_type, $entity, $field, $instance, $langcode, $items);
  // calling function to handle conversion when auto conversion is enabled
  _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, $items);

  // Update the thumbnails to be permanent and register with entity
  $thumbnails = _video_field_get_all_thumbnails($field, $items);
  if (!empty($thumbnails)) {
    db_update('file_managed')
      ->fields(array('status' => FILE_STATUS_PERMANENT))
      ->condition('fid', array_keys($thumbnails), 'IN')->execute();
    file_field_insert($entity_type, $entity, $field, $instance, $langcode, $thumbnails);
  }

  // Update the thumbnails to be permanent and register with entity
  $converted = _video_field_get_all_converted($items);
  if (!empty($converted)) {
    file_field_insert($entity_type, $entity, $field, $instance, $langcode, $converted);
  }
}

/**
 * Implements hook_field_update().
 *
 * @todo handle new revisions
 */
function video_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // The derived files are handled first, because when the original file is deleted first,
  // the derived files can not be looked up anymore.

  // Modification of file_field_update().
  // That function can't be called because the logic for finding
  // existing fids is not the same.
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  // Register the thumbnails in file_usage
  $thumbnails = _video_field_get_all_thumbnails($field, $items);
  if (!empty($thumbnails)) {
    db_update('file_managed')
      ->fields(array('status' => FILE_STATUS_PERMANENT))
      ->condition('fid', array_keys($thumbnails), 'IN')->execute();
  }

  // Register the thumbnails in file_usage
  $converted = _video_field_get_all_converted($items);
  $derivedfiles = array_merge($converted, $thumbnails);

  // Build a display of the current FIDs.
  $current_fids = array();
  foreach ($derivedfiles as $item) {
    $current_fids[] = $item['fid'];
  }

  // Create a bare-bones entity so that we can load its previous values.
  $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
  field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT, array('field_id' => $field['id']));

  // Compare the original field values with the ones that are being saved.
  $original_fids = array();
  if (!empty($original->{$field['field_name']}[$langcode])) {
    $original_thumbs = _video_field_get_all_thumbnails($field, $original->{$field['field_name']}[$langcode], $entity_type, $id);
    $original_converted = _video_field_get_all_converted($original->{$field['field_name']}[$langcode], $entity_type, $id);
    $original_derivedfiles = array_merge($original_thumbs, $original_converted);
    foreach ($original_derivedfiles as $original_derivedfile) {
      $original_fids[] = $original_derivedfile['fid'];
      if (isset($original_derivedfile['fid']) && !in_array($original_derivedfile['fid'], $current_fids)) {
        // Decrement the file usage count by 1 and delete the file if possible.
        file_field_delete_file($original_derivedfile, $field, $entity_type, $id);
      }
    }
  }

  // Add new usage entries for newly added files.
  foreach ($derivedfiles as $item) {
    if (!in_array($item['fid'], $original_fids)) {
      $file = (object) $item;
      file_usage_add($file, 'file', $entity_type, $id);
    }
  }

  // Process the original file
  file_field_update($entity_type, $entity, $field, $instance, $langcode, $items);
  _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, $items);
}

/**
 * Implements hook_field_delete().
 */
function video_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // Deregister the thumbnails in file_usage
  $thumbnails = _video_field_get_all_thumbnails($field, $items);
  file_field_delete($entity_type, $entity, $field, $instance, $langcode, $thumbnails);

  // Deregister the converted files in file_usage
  $converted = _video_field_get_all_converted($items);
  file_field_delete($entity_type, $entity, $field, $instance, $langcode, $converted);

  file_field_delete($entity_type, $entity, $field, $instance, $langcode, $items);
}

/**
 * Implements hook_field_delete_revision().
 */
function video_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // Deregister the thumbnails in file_usage
  $thumbnails = _video_field_get_all_thumbnails($field, $items);
  file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $thumbnails);

  // Deregister the converted files in file_usage
  $converted = _video_field_get_all_converted($items);
  file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $converted);

  file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $items);
}

/**
 * Implements hook_field_is_empty().
 */
function video_field_is_empty($item, $field) {
  return file_field_is_empty($item, $field);
}

/**
 * Implements hook_entity_insert().
 *
 * Processes newly uploaded files that should be converted on save.
 */
function video_entity_insert($entity, $type) {
  _video_field_convert_on_save($entity, $type);
}

/**
 * Implements hook_entity_updated().
 *
 * Processes newly uploaded files that should be converted on save.
 */
function video_entity_update($entity, $type) {
  _video_field_convert_on_save($entity, $type);
}

/**
 * Implements hook_entity_translation_save().
 *
 * Process saving a "Entity Translation" save.
 */
function video_entity_translation_save($type, $entity, $language) {
  _video_field_convert_on_save($entity, $type);
}

/**
 * Widget
 */

/**
 * Implements hook_field_widget_info().
 */
function video_field_widget_info() {
  return array(
    'video_upload' => array(
      'label' => t('Video Upload'),
      'field types' => array('video'),
      'settings' => array(
        'progress_indicator' => 'throbber',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_settings_form().
 */
function video_field_widget_settings_form($field, $instance) {
  // Use the file widget settings form.
  return file_field_widget_settings_form($field, $instance);
}

/**
 * Implements hook_field_widget_form().
 */
function video_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Add display_field setting to field because file_field_widget_form() assumes it is set.
  $field['settings']['display_field'] = 0;

  $elements = file_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
  $settings = $instance['settings'];

  foreach (element_children($elements) as $delta) {
    // If not using custom extension validation, ensure this is an video.
    $supported_extensions = array_keys(video_utility::getVideoExtensions());
    $extensions = isset($elements[$delta]['#upload_validators']['file_validate_extensions'][0]) ? $elements[$delta]['#upload_validators']['file_validate_extensions'][0] : implode(' ', $supported_extensions);
    $extensions = array_intersect(explode(' ', $extensions), $supported_extensions);
    $elements[$delta]['#upload_validators']['file_validate_extensions'][0] = implode(' ', $extensions);

    // Add all extra functionality provided by the video widget.
    $elements[$delta]['#process'][] = 'video_field_widget_process';

    // Add thumbnail stub to prevent errors in file_ajax_upload().
    $elements[$delta]['thumbnail'] = array(
      '#type' => 'value',
      '#value' => NULL,
    );

    // Override value loader
    $elements[$delta]['#value_callback'] = 'video_field_widget_value';
  }

  if ($field['cardinality'] == 1) {
    // If there's only one field, return it as delta 0.
    if (empty($elements[0]['#default_value']['fid'])) {
      $elements[0]['#description'] = theme('file_upload_help', array('description' => $instance['description'], 'upload_validators' => $elements[0]['#upload_validators']));
    }
  }
  else {
    $elements['#file_upload_description'] = theme('file_upload_help', array('upload_validators' => $elements[0]['#upload_validators']));
  }
  return $elements;
}

/**
 * The #value_callback for the video field element.
 *
 * This function loads additional information related to the video to be used in
 * video_widget_element_settings().
 */
function video_field_widget_value($element, $input = FALSE, $form_state) {
  $value = file_field_widget_value($element, $input, $form_state);

  if ($value['fid'] > 0) {
    $transcoder = new Transcoder();
    if ($transcoder->hasTranscoder()) {
      $video = video_jobs::load($value['fid']);

      if ($video) {
        $value['dimensions'] = $video->dimensions;
        $value['conversionstatus'] = $video->video_status;
      }
    }
  }

  if ($input && !empty($input['dimensions'])) {
    $value['dimensions'] = $input['dimensions'];
  }

  return $value;
}

/**
 * An element #process callback for the video field type.
 */
function video_field_widget_process($element, &$form_state, $form) {
  $item = $element['#value'];
  $item['fid'] = $element['fid']['#value'];
  $field = field_widget_field($element, $form_state);

  $element['#theme'] = 'video_widget';

  // Title is not necessary for each individual field.
  if ($field['cardinality'] != 1) {
    unset($element['#title']);
  }

  // Add our extra fields if in preview mode
  if (empty($item['fid'])) {
    return $element;
  }

  video_widget_element_settings($element, $form_state, $field);
  video_thumb_process($element, $form_state, $field);

  return $element;
}

/**
 * Adds a preview of thumbnails for you to select when uploading videos.
 */
function video_thumb_process(array &$element, array &$form_state, array $field) {
  $file = $element['#value'];
  $fid = intval($file['fid']);
  $defaultthumbfid = isset($field['settings']['default_video_thumbnail']) ? intval($field['settings']['default_video_thumbnail']['fid']) : 0;
  $thumbnailfid = !isset($file['thumbnail']) ? 0 : (is_array($file['thumbnail']) ? intval($file['thumbnail']['fid']) : intval($file['thumbnail']));

  if ($fid != 0) {
    $gen_fail = FALSE;

    if ($field['settings']['autothumbnail'] == 'auto') {
      $transcoder = new Transcoder();
      $thumbs = $transcoder->extractFrames($file, $field);
      $thumbstyle = !empty($field['settings']['preview_video_thumb_style']) ? $field['settings']['preview_video_thumb_style'] : 'thumbnail';

      if (!empty($thumbs)) {
        $thumbss = array();
        foreach ($thumbs as $img) {
          $thumbss[$img->fid] = theme('image_style', array('style_name' => $thumbstyle, 'path' => $img->uri));
        }

        if ($thumbnailfid > 0 && isset($thumbss[$thumbnailfid])) {
          $currentthumb = $thumbnailfid;
        }
        else {
          $currentthumb = array_rand($thumbss);
        }

        $element['thumbnail'] = array(
          '#type' => 'radios',
          '#title' => t('Video thumbnail'),
          '#options' => $thumbss,
          '#default_value' => $currentthumb,
          '#weight' => 10,
          '#attributes' => array('class' => array('video-thumbnails'), 'onchange' => 'Drupal.behaviors.videoEdit()', 'rel' => 'video_large_thumbnail-' . $fid),
        );
      }
      elseif ($thumbs === FALSE) {
        $gen_fail = TRUE;
      }
    }

    if ($gen_fail || $field['settings']['autothumbnail'] == 'manual_upload') {
      $file += (array) file_load($fid);
      $scheme = isset($field['settings']['uri_scheme_thumbnails']) ? $field['settings']['uri_scheme_thumbnails'] : 'public';
      $element['thumbnail'] = array(
        '#title' => t('Video thumbnail'),
        '#type' => 'managed_file',
        '#description' => t('The uploaded image will be used as video thumbnail on this video.'),
        '#default_value' => NULL,
        '#upload_location' => $scheme . '://' . variable_get('video_thumbnail_path', 'videos/thumbnails') . '/' . $fid,
        '#weight' => 10,
      );

      // Set the current thumbnail fid, if it is not the default one
      if ($thumbnailfid > 0) {
        if ($defaultthumbfid == 0 || $thumbnailfid != $defaultthumbfid) {
          $element['thumbnail']['#default_value'] = $thumbnailfid;
        }
        else {
          // Unset the form_state value for the thumbnail field if it is the default thumbnail.
          // This prevents the "may not be referenced" error.
          form_set_value($element, NULL, $form_state);
        }
      }
    }

    // Setup our large thumbnail that is on the left.
    if (!empty($field['settings']['preview_video_thumb_style'])) {
      $large_thumb = NULL;
      if (!empty($currentthumb)) {
        $large_thumb = file_load($currentthumb);
      }
      elseif ($thumbnailfid > 0) {
        $large_thumb = file_load($thumbnailfid);
      }
      elseif ($defaultthumbfid > 0) {
        $large_thumb = file_load($defaultthumbfid);
      }

      if (!empty($large_thumb)) {
        $element['preview']['#markup'] = '<div class="video-preview video_large_thumbnail-' . $fid . '">' . theme('image_style', array('style_name' => $field['settings']['preview_video_thumb_style'], 'path' => $large_thumb->uri)) . '</div>';
      }
    }
  }
}

/**
 * Process elements loads on settings
 */
function video_widget_element_settings(array &$element, array &$form_state, array $field) {
  $transcoder = new Transcoder();

  $file = $element['#value'];
  $delta = $element['#delta'];

  $instance = field_widget_instance($element, $form_state);
  $dimensions = $instance['settings']['default_dimensions'];
  $default_dimensions = user_access('override player dimensions');
  $autoconversion = !empty($field['settings']['autoconversion']) && $transcoder->hasTranscoder();

  $description = t('Set the size of the converted video.');
  $options = video_utility::getDimensions();
  if ($autoconversion && $file['fid'] != 0 && $default_dimensions) {
    $file_object = file_load($file['fid']);
    $video_info = _video_dimensions_options($options, $file_object);
    if (!empty($video_info['width']) && !empty($video_info['height'])) {
      $dimensions = $video_info['width'] . 'x' . $video_info['height'];
      $description .= ' ' . t('The original 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, black bars will be added to maintain the original aspect ratio.', array('%size' => $dimensions));
    }
  }

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

  // show only enabled the autoconversion
  if ($autoconversion) {
    $element['dimensions'] = array(
      '#type' => 'select',
      '#title' => t('Output video dimensions'),
      '#default_value' => $dimensions,
      '#description' => $description,
      '#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;
  }

  // only in preview mode and then create thumbnails
  if ($autoconversion) {
    // check if already converted or failed
    if (user_access('re convert video') && isset($file['conversionstatus']) && ($file['conversionstatus'] == VIDEO_RENDERING_COMPLETE || $file['conversionstatus'] == VIDEO_RENDERING_FAILED)) {
      $status = array(VIDEO_RENDERING_COMPLETE => 'was successful', VIDEO_RENDERING_FAILED => 'failed');
      $element['re_convert_video'] = array(
        '#type' => 'checkbox',
        '#title' => t('Video conversion ' . $status[$file['conversionstatus']] . '. Re-queue video conversion?'),
        '#description' => t('This will re-convert your video and schedule it for cron, unless you also check “convert video on save,” below.'),
        '#attributes' => array('class' => array('video-re-convert', 'video-' . $file['conversionstatus'])),
      );
    }
    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 video will not convert your video when you save, and it will not be scheduled for cron.'),
        '#attributes' => array('class' => array('video-bypass-auto-conversion')),
      );
    }
    elseif (variable_get('video_bypass_conversion', FALSE)) {
      $element['bypass_autoconversion'] = array(
        '#type' => 'value',
        '#value' => variable_get('video_bypass_conversion', FALSE),
      );
    }
    // check this to convert the video on save
    if (user_access('convert on submission')) {
      $element['convert_video_on_save'] = array(
        '#type' => 'checkbox',
        '#title' => t('Convert video on save'),
        '#default_value' => variable_get('video_convert_on_save', FALSE),
        '#description' => t('This will convert your video on save, instead of scheduling it for cron.'),
        '#attributes' => array('class' => array('video-convert-video-on-save')),
      );
    }
    elseif (variable_get('video_convert_on_save', FALSE)) {
      $element['convert_video_on_save'] = array(
        '#type' => 'value',
        '#value' => variable_get('video_convert_on_save', FALSE),
      );
    }
  }

  // use of default thumbnail
  if (!empty($field['settings']['default_video_thumbnail']['fid'])) {
    $defaultfid = $field['settings']['default_video_thumbnail']['fid'];

    $default_thumb = (isset($file['thumbnail']) && $defaultfid == $file['thumbnail']) || 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 output.'),
        '#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,
      );
    }
  }
}

/**
 * Updates options list to show matching aspect ratios and matching resolutions
 *
 * 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);

  if (empty($aspect_ratio)) {
    return $aspect_ratio;
  }

  // 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 of original file') . ')';
    }
    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 of original file') . ')';
      }
    }
  }

  return $aspect_ratio;
}

/**
 * Returns the width/height and aspect ratio of the video
 */
function _video_aspect_ratio($video) {
  $transcoder = new Transcoder();
  $transcoder = $transcoder->getTranscoder();
  $transcoder->setInput((array) $video);
  $wxh = $transcoder->getDimensions();

  if (empty($wxh) || empty($wxh['width']) || empty($wxh['height'])) {
    // No width and height found. This may be because the transcoder does not support retrieving dimensions.
    return NULL;
  }

  return array(
    'width' => $wxh['width'],
    'height' => $wxh['height'],
    'ratio' => number_format($wxh['width'] / $wxh['height'], 4),
  );
}

/**
 * Formatters
 */

/**
 * Implements hook_field_formatter_info().
 */
function video_field_formatter_info() {
  return array(
    'video_formatter_player' => array(
      'label' => t('Video player'),
      'field types' => array('video'),
      'settings' => array(
        'widthxheight' => '640x360',
        'poster_image_style' => '',
      ),
    ),
    'video_formatter_thumbnail' => array(
      'label' => t('Video thumbnail'),
      'field types' => array('video'),
      'settings' => array(
        'image_style' => '',
        'image_link' => '',
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function video_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $image_styles = image_style_options(FALSE);

  switch ($display['type']) {
    case 'video_formatter_thumbnail':
      $element['image_style'] = array(
        '#title' => t('Video thumbnail style'),
        '#type' => 'select',
        '#default_value' => $settings['image_style'],
        '#empty_option' => t('None (original video thumbnail)'),
        '#options' => $image_styles,
      );

      $element['image_link'] = array(
        '#title' => t('Link video or video thumbnail to'),
        '#type' => 'select',
        '#default_value' => $settings['image_link'],
        '#empty_option' => t('Nothing'),
        '#options' => array(
          'content' => t('Content'),
          'file' => t('File'),
        ),
      );
      break;

    case 'video_formatter_player':
      $element['widthxheight'] = array(
        '#title' => t('Dimensions'),
        '#type' => 'select',
        '#default_value' => $settings['widthxheight'],
        '#description' => t('Select the desired dimensions of the video player. You can add your own dimensions at !settings.', array('!settings' => l(t('video module settings'), 'admin/config/media/video'))),
        '#options' => video_utility::getDimensions(),
      );

      $element['poster_image_style'] = array(
        '#title' => t('Poster image style'),
        '#type' => 'select',
        '#default_value' => $settings['poster_image_style'],
        '#empty_option' => t('None (original image)'),
        '#description' => t('The original video thumbnail will be displayed. Otherwise, you can add a custom image style at !settings.', array('!settings' => l(t('media image styles'), 'admin/config/media/image-styles'))),
        '#options' => $image_styles,
      );
      break;
  }

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function video_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();
  $image_styles = image_style_options(FALSE);
  // Unset possible 'No defined styles' option.
  unset($image_styles['']);

  // Styles could be lost because of enabled/disabled modules that defines
  // their styles in code.
  switch ($display['type']) {
    case 'video_formatter_thumbnail':
      if (isset($image_styles[$settings['image_style']])) {
        $summary[] = t('Video thumbnail style: @style', array('@style' => $image_styles[$settings['image_style']]));
      }
      else {
        $summary[] = t('Original video thumbnail');
      }

      $link_types = array(
        'content' => t('Linked to content'),
        'file' => t('Linked to video file'),
      );
      // Display this setting only if image is linked.
      if (isset($link_types[$settings['image_link']])) {
        $summary[] = $link_types[$settings['image_link']];
      }
      break;

    case 'video_formatter_player':
      $summary[] = t('Player dimensions: @widthxheight', array('@widthxheight' => $settings['widthxheight']));
      if (isset($image_styles[$settings['poster_image_style']])) {
        $summary[] = t('Poster image style: @style', array('@style' => $image_styles[$settings['poster_image_style']]));
      }
      break;
  }

  return implode('<br />', $summary);
}

/**
 * Implements hook_field_formatter_view().
 */
function video_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    switch ($display['type']) {
      case 'video_formatter_thumbnail':
        // Check if the formatter involves a link.
        if ($settings['image_link'] == 'content') {
          $uri = entity_uri($entity_type, $entity);
        }
        elseif ($settings['image_link'] == 'file') {
          $link_file = TRUE;
        }
        if (isset($link_file)) {
          $uri = array(
            'path' => file_create_url($item['uri']),
            'options' => array(),
          );
        }
        $element[$delta] = array(
          '#theme' => 'video_formatter_thumbnail',
          '#item' => $item,
          '#image_style' => $settings['image_style'],
          '#path' => isset($uri) ? $uri : '',
          '#entity' => $entity,
          '#entity_type' => $entity_type,
          '#field' => $field,
          '#instance' => $instance
        );
        break;

      case 'video_formatter_player':
        $element[$delta] = array(
          '#theme' => 'video_formatter_player',
          '#item' => $item,
          '#entity' => $entity,
          '#entity_type' => $entity_type,
          '#field' => $field,
          '#instance' => $instance,
          '#player_dimensions' => $settings['widthxheight'],
          '#poster_image_style' => $settings['poster_image_style'],
        );
        break;
    }
  }

  return $element;
}

/**
 * Implements hook_filefield_sources_widgets().
 */
function video_filefield_sources_widgets() {
  return array('video_upload');
}

/**
 * Video file save to the video_queue table for conversions
 */
function _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, &$items) {
  $transcoder = new Transcoder();

  if (empty($field['settings']['autoconversion']) || !$transcoder->hasTranscoder()) {
    return;
  }

  foreach ($items as $delta => &$item) {
    $fid = intval($item['fid']);
    // skip adding entry if bypass conversion is checked
    if (!empty($item['bypass_autoconversion'])) {
      // delete the conversion job if any
      video_jobs::delete($fid);
      return;
    }

    // Try to load the job
    $video = video_jobs::load($fid);

    // Create the job if it doesn't exist
    if (!$video) {
      list($entity_id, $entity_vid, $bundle) = entity_extract_ids($entity_type, $entity);
      // @todo get the default dimension when not available in $item
      if (!video_jobs::create($item['fid'], $item['dimensions'], $entity_id, $entity_type, $field['field_name'], $langcode, $delta)) {
        drupal_set_message(t('Something went wrong with your video job creation. Please check your recent log entries for further debugging.'), 'error');
        return;
      }
      // Load a fresh copy of the job
      $video = video_jobs::load($fid);
    }

    // re queue for video conversion
    if (!empty($item['re_convert_video'])) {
      $video->video_status = VIDEO_RENDERING_PENDING;
      $video->statusupdated = time();
      $video->dimensions = $item['dimensions'];
      video_jobs::update($video);
    }

    if ($video->video_status == VIDEO_RENDERING_PENDING) {
      // Convert on save if the job is pending and if it is requested
      // The automatic conversions of files is handled in _video_field_convert_on_save(),
      // which is called from hook_entity_insert/hook_entity_update.
      if (!empty($item['convert_video_on_save'])) {
        // Only save the fid, because the location of the file may change
        // between now and _video_field_convert_on_save().
        $entity->video_convert_on_save[$video->fid] = $video->fid;
      }
      else {
        drupal_set_message(t('Transcoding job was successfully queued for %transcoder-name. The video %video-name will be converted soon.', array('%transcoder-name' => $transcoder->getTranscoder()->getName(), '%video-name' => $video->filename)));
      }
    }
  }
}

/**
 * Processes video fields that should convert on save.
 *
 * This is not performed in _video_field_file_autoconversion() because
 * of incompatibilities with Rules and File(field) Paths.
 *
 * When hook_entity_insert/update are called, all field related operations
 * are complete and the entity is fully saved to the database. This
 * allows Rules to supply a proper entity to the event handlers.
 *
 * The $entity->video_convert_on_save property is set in
 * _video_field_file_autoconversion().
 */
function _video_field_convert_on_save($entity, $type) {
  if (!empty($entity->video_convert_on_save)) {
    $transcoder = new Transcoder();
    $transcodername = $transcoder->getTranscoder()->getName();

    foreach ($entity->video_convert_on_save as $videofid) {
      $video = video_jobs::load($videofid);
      if ($transcoder->executeConversion($video)) {
        if ($video->video_status == VIDEO_RENDERING_COMPLETE) {
          drupal_set_message(t('The video %video-name was converted.', array('%video-name' => $video->filename)));
        }
        else {
          drupal_set_message(t('Transcoding job was successfully submitted to %transcoder-name. The video %video-name will be converted soon.', array('%transcoder-name' => $transcodername, '%video-name' => $video->filename)));
        }
      }
      else {
        drupal_set_message(t('Something went wrong with transcoding %video-name. Please check your <a href="@log-page">recent log entries</a> for further debugging.', array('%video-name' => $video->filename, '@log-page' => url('admin/reports/dblog'))), 'error');
      }
    }

    unset($entity->video_convert_on_save);
  }
}

function _video_field_get_all_thumbnails(array $field, array $items, $usage_entity_type = NULL, $usage_entity_id = NULL) {
  if (empty($items)) {
    return array();
  }

  $defaultthumbnailfid = !empty($field['settings']['default_video_thumbnail']) ? $field['settings']['default_video_thumbnail']['fid'] : 0;
  $videofids = array();
  $thumbnailfids = array();
  foreach ($items as $item) {
    if (!empty($item['fid'])) {
      $videofids[] = intval($item['fid']);

      // Add the selected thumbnail if it is not the default thumbnail for the field
      if (!empty($item['thumbnail']) && $item['thumbnail'] != $defaultthumbnailfid) {
        $thumbnailfids[] = intval($item['thumbnail']);
      }
    }
  }

  if (empty($videofids)) {
    return array();
  }

  // Add the automatically extracted thumbnails
  $query = db_select('video_thumbnails', 't')
    ->fields('t', array('thumbnailfid'))
    ->condition('videofid', $videofids, 'IN');

  // Only return files with usage when requested
  if ($usage_entity_type != NULL && $usage_entity_id != NULL) {
    $query->innerJoin('file_usage', 'u', 'u.fid = t.thumbnailfid AND u.type = :type AND u.id = :id', array(
        ':type' => $usage_entity_type,
        ':id' => $usage_entity_id,
    ));
  }

  $thumbnailfids = array_merge($thumbnailfids, $query->execute()->fetchCol(0));

  return video_utility::objectToArray(file_load_multiple($thumbnailfids));
}

function _video_field_get_all_converted(array $items, $usage_entity_type = NULL, $usage_entity_id = NULL) {
  if (empty($items)) {
    return array();
  }

  $videofids = array();
  foreach ($items as $item) {
    if (!empty($item['fid'])) {
      $videofids[] = intval($item['fid']);
    }
  }

  if (empty($videofids)) {
    return array();
  }

  $query = db_select('video_output', 't')
    ->fields('t', array('output_fid'))
    ->condition('original_fid', $videofids, 'IN');

  // Only return files with usage when requested
  if ($usage_entity_type != NULL && $usage_entity_id != NULL) {
    $query->innerJoin('file_usage', 'u', 'u.fid = t.output_fid AND u.type = :type AND u.id = :id', array(
      ':type' => $usage_entity_type,
      ':id' => $usage_entity_id,
    ));
  }

  $convertedfids = $query->execute()->fetchCol(0);

  return video_utility::objectToArray(file_load_multiple($convertedfids));
}