4 * Implement a video field, based on the file module's file field.
8 * Implements hook_field_info().
10 function video_field_info() {
13 'label' => t('Video'),
14 'description' => t('This field stores the ID of a video file as an integer value.'),
16 'uri_scheme' => variable_get('file_default_scheme', 'public'),
17 'uri_scheme_converted' => variable_get('file_default_scheme', 'public'),
18 'uri_scheme_thumbnails' => variable_get('file_default_scheme', 'public'),
19 'thumbnail_format' => 'jpg',
20 'autoconversion' => 1,
21 'autothumbnail' => 'auto',
22 'default_video_thumbnail' => 0,
23 'preview_video_thumb_style' => 'thumbnail',
26 'instance_settings' => array(
27 'file_extensions' => 'mp4 ogg avi mov wmv flv ogv webm',
28 'file_directory' => 'videos/original',
30 'default_dimensions' => '640x360',
32 'default_widget' => 'video_upload',
33 'default_formatter' => 'video_formatter_player',
39 * Implements hook_field_settings_form().
41 function video_field_settings_form($field, $instance, $has_data) {
42 $transcoder = new
Transcoder();
43 $hastranscoder = $transcoder->hasTranscoder();
45 $defaults = field_info_field_settings($field['type']);
46 $settings = array_merge($defaults, $field['settings']);
48 // Copied from file_field_settings_form().
49 $scheme_options = array();
50 foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE
) as
$scheme => $stream_wrapper) {
51 $scheme_options[$scheme] = $stream_wrapper['name'];
53 $form['uri_scheme'] = array(
55 '#title' => t('Upload destination of original file'),
56 '#options' => $scheme_options,
57 '#default_value' => $settings['uri_scheme'],
58 '#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.'),
60 $form['uri_scheme_converted'] = array(
62 '#title' => t('Upload destination of converted files'),
63 '#options' => $scheme_options,
64 '#default_value' => $settings['uri_scheme_converted'],
65 '#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.'),
66 '#access' => $hastranscoder,
68 $form['uri_scheme_thumbnails'] = array(
70 '#title' => t('Upload destination of thumbnails'),
71 '#options' => $scheme_options,
72 '#default_value' => $settings['uri_scheme_thumbnails'],
73 '#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.'),
74 '#access' => $hastranscoder,
77 // Add warnings for S3
78 if ($hastranscoder && isset($scheme_options['s3'])) {
79 $value = $transcoder->getTranscoder()->getValue();
81 if ($value == 'TranscoderAbstractionFactoryFfmpeg') {
82 $form['uri_scheme']['#description'] .
= '<br/>';
83 $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']));
86 $form['uri_scheme_thumbnails']['#description'] .
= '<br/>';
87 $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']));
90 // Add warnings for streaming to iPad when using the private file system
91 // See http://www.metaltoad.com/blog/iphone-video-streaming-drupals-file-system
92 if (isset($scheme_options['private']) && !module_exists('xsendfile') && !module_exists('resumable_download')) {
93 $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')));
94 $form['uri_scheme']['#description'] .
= $ioswarning;
95 $form['uri_scheme_converted']['#description'] .
= $ioswarning;
98 $form['autoconversion'] = array(
99 '#type' => 'checkbox',
100 '#title' => t('Enable auto video conversion'),
101 '#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(
102 '!settings' => l(t('transcoder settings'), 'admin/config/media/video/transcoders'),
103 '!preset' => l(t('preset settings'), 'admin/config/media/video/presets'),
105 '#default_value' => isset($settings['autoconversion']) ?
$settings['autoconversion'] : '',
106 '#access' => $hastranscoder,
109 $form['thumbnail_format'] = array(
110 '#title' => t('Thumbnail format'),
112 '#options' => array('jpg' => 'JPEG', 'png' => 'PNG'),
113 '#default_value' => !empty($settings['thumbnail_format']) ?
$settings['thumbnail_format'] : 'jpg',
114 '#access' => $hastranscoder,
117 $thumb_options = array(
118 'auto' => 'Automatically extract thumbnails from video (with fallback to manual upload)',
119 'manual_upload' => 'Manually upload a thumbnail',
120 'no' => 'Don\'t create thumbnail',
123 // When there is no transcoder, the auto option is not available and should not be the default.
124 if (!$hastranscoder) {
125 unset($thumb_options['auto']);
126 if (!isset($settings['autothumbnail']) || $settings['autothumbnail'] == 'auto') {
127 $settings['autothumbnail'] = 'no';
131 $form['autothumbnail'] = array(
133 '#title' => t('Video thumbnails'),
134 '#options' => $thumb_options,
135 '#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'))),
136 '#default_value' => isset($settings['autothumbnail']) ?
$settings['autothumbnail'] : 'auto',
139 $form['default_video_thumbnail'] = array(
140 '#title' => t('Default video thumbnail'),
141 '#type' => 'managed_file',
142 '#element_validate' => array('video_field_default_thumbnail_validate'),
143 '#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.'),
144 '#default_value' => !empty($settings['default_video_thumbnail']['fid']) ?
$settings['default_video_thumbnail']['fid'] : '',
145 '#upload_location' => 'public://videos/thumbnails/default',
148 $form['preview_video_thumb_style'] = array(
149 '#title' => t('Preview thumbnail style'),
151 '#options' => image_style_options(FALSE
),
152 '#empty_option' => '<' .
t('no preview') .
'>',
153 '#default_value' => !empty($settings['preview_video_thumb_style']) ?
$settings['preview_video_thumb_style'] : '',
154 '#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.'),
157 $selectedpresets = array_filter(variable_get('video_preset', array()));
158 $presets = Preset
::getAllPresets();
159 $presetnames = array();
160 foreach ($presets as
$preset) {
161 $presetnames[$preset['name']] = $preset['name'];
163 if (in_array($preset['name'], $selectedpresets)) {
164 $presetnames[$preset['name']] .
= ' (' .
t('default') .
')';
168 $form['presets'] = array(
169 '#title' => t('Presets'),
170 '#type' => 'checkboxes',
171 '#options' => $presetnames,
172 '#default_value' => !empty($settings['presets']) ?
$settings['presets'] : array(),
173 '#description' => t('If any presets are selected, these presets will be used for this field instead of the default presets.'),
174 '#access' => $hastranscoder,
181 * Element specific validation for video default value.
183 function video_field_default_thumbnail_validate($element, &$form_state) {
184 $settings = $form_state['values']['field']['settings'];
185 // Make the file permanent and store it in the form.
186 if (!empty($settings['default_video_thumbnail']['fid'])) {
187 $file = file_load($settings['default_video_thumbnail']['fid']);
188 $file->status
= FILE_STATUS_PERMANENT
;
189 $file = file_save($file);
190 $form_state['values']['field']['settings']['default_video_thumbnail'] = (array) $file;
195 * Implements hook_field_instance_settings_form().
197 function video_field_instance_settings_form(array $field, array $instance) {
198 $widget = $instance['settings'];
200 // Use the file field instance settings form as a basis.
201 $form = file_field_instance_settings_form($field, $instance);
203 // Remove the description option.
204 unset($form['description_field']);
206 $form['default_dimensions'] = array(
208 '#title' => t('Output video dimensions'),
209 '#default_value' => !empty($widget['default_dimensions']) ?
$widget['default_dimensions'] : '',
210 '#options' => video_utility
::getDimensions(),
211 '#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.'),
219 * Implements hook_field_load().
221 function video_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
222 file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);
224 // Load all files we need for these entities
225 $videofids = array();
227 foreach ($entities as
$id => $entity) {
228 // Load the files from the files table.
229 foreach ($items[$id] as
$delta => $item) {
230 if (empty($item) || empty($item['fid'])) {
233 $videofids[] = $item['fid'];
234 if (!empty($item['thumbnail'])) {
235 $fids[] = $item['thumbnail'];
240 if (empty($videofids)) {
245 $queues = db_select('video_queue', 'q')
247 ->condition('q.fid', $videofids, 'IN')->execute()->fetchAllAssoc('fid');
249 // Load the derived files
250 $outputs = db_select('video_output', 'vo')
252 ->condition('vo.original_fid', $videofids, 'IN')
253 ->execute()->fetchAllAssoc('output_fid');
255 $fids = array_merge($fids, array_keys($outputs));
256 $files = file_load_multiple($fids);
258 // Apply the found information to all files for all entities
259 foreach ($entities as
$id => $entity) {
260 foreach ($items[$id] as
$delta => $item) {
261 if (empty($item) || empty($item['fid'])) {
264 // Check whether transcoding is enabled for this file
265 if (isset($queues[$item['fid']])) {
266 $items[$id][$delta]['autoconversion'] = TRUE
;
267 $items[$id][$delta]['conversioncompleted'] = $queues[$item['fid']]->status
== VIDEO_RENDERING_COMPLETE
;
268 $items[$id][$delta]['conversionstatus'] = $queues[$item['fid']]->status
;
270 // Load converted files
271 $items[$id][$delta]['playablefiles'] = array();
272 foreach ($outputs as
$outputfid => $output) {
273 if ($output->original_fid
== $items[$id][$delta]['fid'] && isset($files[$outputfid]) && $files[$outputfid]->filesize > 0) {
274 $conv = (array)$files[$outputfid] + (array)$output;
275 $items[$id][$delta]['playablefiles'][] = (object)$conv;
279 // If for some reason there are no playable files, mark the status as failed
280 if (empty($items[$id][$delta]['playablefiles']) && $items[$id][$delta]['conversioncompleted']) {
281 $items[$id][$delta]['conversioncompleted'] = FALSE
;
282 $items[$id][$delta]['conversionstatus'] = VIDEO_RENDERING_FAILED
;
286 $items[$id][$delta]['playablefiles'] = array((object)$items[$id][$delta]);
287 $items[$id][$delta]['autoconversion'] = FALSE
;
291 if (empty($item['thumbnail']) || !isset($files[$item['thumbnail']])) {
292 $items[$id][$delta]['thumbnail'] = NULL
;
293 $items[$id][$delta]['thumbnailfile'] = NULL
;
296 $items[$id][$delta]['thumbnailfile'] = $files[$item['thumbnail']];
303 * Implements hook_field_validate().
305 * This allows field validation even when the file is added programmatically to
306 * the entity. The function only validates new files, not files that have been
307 * added to the entity before.
309 function video_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
310 $current_fids = array();
312 // Get the video fids
313 foreach ($items as
$delta => $item) {
314 if (empty($item['fid'])) {
317 $current_fids[$item['fid']] = $item['fid'];
320 if (empty($current_fids)) {
324 // Create a bare-bones entity so that we can load its previous values.
325 list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
326 $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
327 field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT
, array('field_id' => $field['id']));
329 // Remove the entries from $current_fids that are already present in the database,
330 // leaving the ones that are new during this save operation.
331 if (!empty($original->{$field['field_name']}[$langcode])) {
332 foreach ($original->{$field['field_name']}[$langcode] as
$originalitem) {
333 if (isset($originalitem['fid']) && isset($current_fids[$originalitem['fid']])) {
334 unset($current_fids[$originalitem['fid']]);
339 if (empty($current_fids)) {
340 // No new files have been added, only new files are checked
344 $current_files = file_load_multiple($current_fids);
345 $validators = file_field_widget_upload_validators($field, $instance);
346 if (empty($validators)) {
347 // No validation rules
351 // Validate the new entries
352 foreach ($items as
$delta => $item) {
353 if (empty($item['fid']) || !isset($current_files[$item['fid']])) {
357 $fileerrors = file_validate($current_files[$item['fid']], $validators);
359 foreach ($fileerrors as
$fileerror) {
360 $errors[$field['field_name']][$langcode][$delta][] = array(
361 'error' => 'video_upload',
362 'message' => $fileerror,
369 * Implements hook_field_widget_error().
371 * Work-around for Drupal bug http://drupal.org/node/1432732
373 function video_field_widget_error($element, $error, $form, &$form_state) {
374 form_error($element, $error['message']);
378 * Implements hook_field_presave().
380 function video_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
381 // change the thumbnails if default is checked
382 foreach ($items as
$delta => $item) {
383 if (!empty($field['settings']['default_video_thumbnail']['fid'])) {
384 if (!empty($item['use_default_video_thumb'])) {
385 $items[$delta]['thumbnail'] = $field['settings']['default_video_thumbnail']['fid'];
390 file_field_presave($entity_type, $entity, $field, $instance, $langcode, $items);
394 * Implements hook_field_insert().
396 function video_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
397 file_field_insert($entity_type, $entity, $field, $instance, $langcode, $items);
398 // calling function to handle conversion when auto conversion is enabled
399 _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, $items);
401 // Update the thumbnails to be permanent and register with entity
402 $thumbnails = _video_field_get_all_thumbnails($field, $items);
403 if (!empty($thumbnails)) {
404 db_update('file_managed')
405 ->fields(array('status' => FILE_STATUS_PERMANENT
))
406 ->condition('fid', array_keys($thumbnails), 'IN')->execute();
407 file_field_insert($entity_type, $entity, $field, $instance, $langcode, $thumbnails);
410 // Update the thumbnails to be permanent and register with entity
411 $converted = _video_field_get_all_converted($items);
412 if (!empty($converted)) {
413 file_field_insert($entity_type, $entity, $field, $instance, $langcode, $converted);
418 * Implements hook_field_update().
420 * @todo handle new revisions
422 function video_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
423 // The derived files are handled first, because when the original file is deleted first,
424 // the derived files can not be looked up anymore.
426 // Modification of file_field_update().
427 // That function can't be called because the logic for finding
428 // existing fids is not the same.
429 list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
431 // Register the thumbnails in file_usage
432 $thumbnails = _video_field_get_all_thumbnails($field, $items);
433 if (!empty($thumbnails)) {
434 db_update('file_managed')
435 ->fields(array('status' => FILE_STATUS_PERMANENT
))
436 ->condition('fid', array_keys($thumbnails), 'IN')->execute();
439 // Register the thumbnails in file_usage
440 $converted = _video_field_get_all_converted($items);
441 $derivedfiles = array_merge($converted, $thumbnails);
443 // Build a display of the current FIDs.
444 $current_fids = array();
445 foreach ($derivedfiles as
$item) {
446 $current_fids[] = $item['fid'];
449 // Create a bare-bones entity so that we can load its previous values.
450 $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
451 field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT
, array('field_id' => $field['id']));
453 // Compare the original field values with the ones that are being saved.
454 $original_fids = array();
455 if (!empty($original->{$field['field_name']}[$langcode])) {
456 $original_thumbs = _video_field_get_all_thumbnails($field, $original->{$field['field_name']}[$langcode], $entity_type, $id);
457 $original_converted = _video_field_get_all_converted($original->{$field['field_name']}[$langcode], $entity_type, $id);
458 $original_derivedfiles = array_merge($original_thumbs, $original_converted);
459 foreach ($original_derivedfiles as
$original_derivedfile) {
460 $original_fids[] = $original_derivedfile['fid'];
461 if (isset($original_derivedfile['fid']) && !in_array($original_derivedfile['fid'], $current_fids)) {
462 // Decrement the file usage count by 1 and delete the file if possible.
463 file_field_delete_file($original_derivedfile, $field, $entity_type, $id);
468 // Add new usage entries for newly added files.
469 foreach ($derivedfiles as
$item) {
470 if (!in_array($item['fid'], $original_fids)) {
471 $file = (object) $item;
472 file_usage_add($file, 'file', $entity_type, $id);
476 // Process the original file
477 file_field_update($entity_type, $entity, $field, $instance, $langcode, $items);
478 _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, $items);
482 * Implements hook_field_delete().
484 function video_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
485 // Deregister the thumbnails in file_usage
486 $thumbnails = _video_field_get_all_thumbnails($field, $items);
487 file_field_delete($entity_type, $entity, $field, $instance, $langcode, $thumbnails);
489 // Deregister the converted files in file_usage
490 $converted = _video_field_get_all_converted($items);
491 file_field_delete($entity_type, $entity, $field, $instance, $langcode, $converted);
493 file_field_delete($entity_type, $entity, $field, $instance, $langcode, $items);
497 * Implements hook_field_delete_revision().
499 function video_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
500 // Deregister the thumbnails in file_usage
501 $thumbnails = _video_field_get_all_thumbnails($field, $items);
502 file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $thumbnails);
504 // Deregister the converted files in file_usage
505 $converted = _video_field_get_all_converted($items);
506 file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $converted);
508 file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, $items);
512 * Implements hook_field_is_empty().
514 function video_field_is_empty($item, $field) {
515 return file_field_is_empty($item, $field);
519 * Implements hook_entity_insert().
521 * Processes newly uploaded files that should be converted on save.
523 function video_entity_insert($entity, $type) {
524 _video_field_convert_on_save($entity, $type);
528 * Implements hook_entity_updated().
530 * Processes newly uploaded files that should be converted on save.
532 function video_entity_update($entity, $type) {
533 _video_field_convert_on_save($entity, $type);
537 * Implements hook_entity_translation_save().
539 * Process saving a "Entity Translation" save.
541 function video_entity_translation_save($type, $entity, $language) {
542 _video_field_convert_on_save($entity, $type);
550 * Implements hook_field_widget_info().
552 function video_field_widget_info() {
554 'video_upload' => array(
555 'label' => t('Video Upload'),
556 'field types' => array('video'),
558 'progress_indicator' => 'throbber',
560 'behaviors' => array(
561 'multiple values' => FIELD_BEHAVIOR_CUSTOM
,
562 'default value' => FIELD_BEHAVIOR_NONE
,
569 * Implements hook_field_widget_settings_form().
571 function video_field_widget_settings_form($field, $instance) {
572 // Use the file widget settings form.
573 return file_field_widget_settings_form($field, $instance);
577 * Implements hook_field_widget_form().
579 function video_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
580 // Add display_field setting to field because file_field_widget_form() assumes it is set.
581 $field['settings']['display_field'] = 0;
583 $elements = file_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
584 $settings = $instance['settings'];
586 foreach (element_children($elements) as
$delta) {
587 // If not using custom extension validation, ensure this is an video.
588 $supported_extensions = array_keys(video_utility
::getVideoExtensions());
589 $extensions = isset($elements[$delta]['#upload_validators']['file_validate_extensions'][0]) ?
$elements[$delta]['#upload_validators']['file_validate_extensions'][0] : implode(' ', $supported_extensions);
590 $extensions = array_intersect(explode(' ', $extensions), $supported_extensions);
591 $elements[$delta]['#upload_validators']['file_validate_extensions'][0] = implode(' ', $extensions);
593 // Add all extra functionality provided by the video widget.
594 $elements[$delta]['#process'][] = 'video_field_widget_process';
596 // Add thumbnail stub to prevent errors in file_ajax_upload().
597 $elements[$delta]['thumbnail'] = array(
602 // Override value loader
603 $elements[$delta]['#value_callback'] = 'video_field_widget_value';
606 if ($field['cardinality'] == 1) {
607 // If there's only one field, return it as delta 0.
608 if (empty($elements[0]['#default_value']['fid'])) {
609 $elements[0]['#description'] = theme('file_upload_help', array('description' => $instance['description'], 'upload_validators' => $elements[0]['#upload_validators']));
613 $elements['#file_upload_description'] = theme('file_upload_help', array('upload_validators' => $elements[0]['#upload_validators']));
619 * The #value_callback for the video field element.
621 * This function loads additional information related to the video to be used in
622 * video_widget_element_settings().
624 function video_field_widget_value($element, $input = FALSE
, $form_state) {
625 $value = file_field_widget_value($element, $input, $form_state);
627 if ($value['fid'] > 0) {
628 $transcoder = new
Transcoder();
629 if ($transcoder->hasTranscoder()) {
630 $video = video_jobs
::load($value['fid']);
633 $value['dimensions'] = $video->dimensions
;
634 $value['conversionstatus'] = $video->video_status
;
639 if ($input && !empty($input['dimensions'])) {
640 $value['dimensions'] = $input['dimensions'];
647 * An element #process callback for the video field type.
649 function video_field_widget_process($element, &$form_state, $form) {
650 $item = $element['#value'];
651 $item['fid'] = $element['fid']['#value'];
652 $field = field_widget_field($element, $form_state);
654 $element['#theme'] = 'video_widget';
656 // Title is not necessary for each individual field.
657 if ($field['cardinality'] != 1) {
658 unset($element['#title']);
661 // Add our extra fields if in preview mode
662 if (empty($item['fid'])) {
666 video_widget_element_settings($element, $form_state, $field);
667 video_thumb_process($element, $form_state, $field);
673 * Adds a preview of thumbnails for you to select when uploading videos.
675 function video_thumb_process(array &$element, array &$form_state, array $field) {
676 $file = $element['#value'];
677 $fid = intval($file['fid']);
678 $defaultthumbfid = isset($field['settings']['default_video_thumbnail']) ?
intval($field['settings']['default_video_thumbnail']['fid']) : 0;
679 $thumbnailfid = !isset($file['thumbnail']) ?
0 : (is_array($file['thumbnail']) ?
intval($file['thumbnail']['fid']) : intval($file['thumbnail']));
684 if ($field['settings']['autothumbnail'] == 'auto') {
685 $transcoder = new
Transcoder();
686 $thumbs = $transcoder->extractFrames($file, $field);
687 $thumbstyle = !empty($field['settings']['preview_video_thumb_style']) ?
$field['settings']['preview_video_thumb_style'] : 'thumbnail';
689 if (!empty($thumbs)) {
691 foreach ($thumbs as
$img) {
692 $thumbss[$img->fid
] = theme('image_style', array('style_name' => $thumbstyle, 'path' => $img->uri
));
695 if ($thumbnailfid > 0 && isset($thumbss[$thumbnailfid])) {
696 $currentthumb = $thumbnailfid;
699 $currentthumb = array_rand($thumbss);
702 $element['thumbnail'] = array(
704 '#title' => t('Video thumbnail'),
705 '#options' => $thumbss,
706 '#default_value' => $currentthumb,
708 '#attributes' => array('class' => array('video-thumbnails'), 'onchange' => 'Drupal.behaviors.videoEdit()', 'rel' => 'video_large_thumbnail-' .
$fid),
711 elseif ($thumbs === FALSE
) {
716 if ($gen_fail || $field['settings']['autothumbnail'] == 'manual_upload') {
717 $file += (array) file_load($fid);
718 $scheme = isset($field['settings']['uri_scheme_thumbnails']) ?
$field['settings']['uri_scheme_thumbnails'] : 'public';
719 $element['thumbnail'] = array(
720 '#title' => t('Video thumbnail'),
721 '#type' => 'managed_file',
722 '#description' => t('The uploaded image will be used as video thumbnail on this video.'),
723 '#default_value' => NULL
,
724 '#upload_location' => $scheme .
'://' .
variable_get('video_thumbnail_path', 'videos/thumbnails') .
'/' .
$fid,
728 // Set the current thumbnail fid, if it is not the default one
729 if ($thumbnailfid > 0) {
730 if ($defaultthumbfid == 0 || $thumbnailfid != $defaultthumbfid) {
731 $element['thumbnail']['#default_value'] = $thumbnailfid;
734 // Unset the form_state value for the thumbnail field if it is the default thumbnail.
735 // This prevents the "may not be referenced" error.
736 form_set_value($element, NULL
, $form_state);
741 // Setup our large thumbnail that is on the left.
742 if (!empty($field['settings']['preview_video_thumb_style'])) {
744 if (!empty($currentthumb)) {
745 $large_thumb = file_load($currentthumb);
747 elseif ($thumbnailfid > 0) {
748 $large_thumb = file_load($thumbnailfid);
750 elseif ($defaultthumbfid > 0) {
751 $large_thumb = file_load($defaultthumbfid);
754 if (!empty($large_thumb)) {
755 $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>';
762 * Process elements loads on settings
764 function video_widget_element_settings(array &$element, array &$form_state, array $field) {
765 $transcoder = new
Transcoder();
767 $file = $element['#value'];
768 $delta = $element['#delta'];
770 $instance = field_widget_instance($element, $form_state);
771 $dimensions = $instance['settings']['default_dimensions'];
772 $default_dimensions = user_access('override player dimensions');
773 $autoconversion = !empty($field['settings']['autoconversion']) && $transcoder->hasTranscoder();
775 $description = t('Set the size of the converted video.');
776 $options = video_utility
::getDimensions();
777 if ($autoconversion && $file['fid'] != 0 && $default_dimensions) {
778 $file_object = file_load($file['fid']);
779 $video_info = _video_dimensions_options($options, $file_object);
780 if (!empty($video_info['width']) && !empty($video_info['height'])) {
781 $dimensions = $video_info['width'] .
'x' .
$video_info['height'];
782 $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));
786 // Override our dimensions to the user selected.
787 if (!empty($file['dimensions'])) {
788 $dimensions = $file['dimensions'];
791 // show only enabled the autoconversion
792 if ($autoconversion) {
793 $element['dimensions'] = array(
795 '#title' => t('Output video dimensions'),
796 '#default_value' => $dimensions,
797 '#description' => $description,
798 '#options' => $options,
801 // If users cannot change the default dimensions, lets change this to a value.
802 if (!$default_dimensions) {
803 $element['dimensions']['#type'] = 'value';
804 $element['dimensions']['#value'] = $dimensions;
807 // only in preview mode and then create thumbnails
808 if ($autoconversion) {
809 // check if already converted or failed
810 if (user_access('re convert video') && isset($file['conversionstatus']) && ($file['conversionstatus'] == VIDEO_RENDERING_COMPLETE
|| $file['conversionstatus'] == VIDEO_RENDERING_FAILED
)) {
811 $status = array(VIDEO_RENDERING_COMPLETE
=> 'was successful', VIDEO_RENDERING_FAILED
=> 'failed');
812 $element['re_convert_video'] = array(
813 '#type' => 'checkbox',
814 '#title' => t('Video conversion ' .
$status[$file['conversionstatus']] .
'. Re-queue video conversion?'),
815 '#description' => t('This will re-convert your video and schedule it for cron, unless you also check “convert video on save,” below.'),
816 '#attributes' => array('class' => array('video-re-convert', 'video-' .
$file['conversionstatus'])),
819 if (user_access('bypass conversion video')) {
820 $element['bypass_autoconversion'] = array(
821 '#type' => 'checkbox',
822 '#title' => t('Bypass auto conversion'),
823 '#default_value' => isset($file['bypass_autoconversion']) ?
$file['bypass_autoconversion'] : variable_get('video_bypass_conversion', FALSE
),
824 '#description' => t('This video will not convert your video when you save, and it will not be scheduled for cron.'),
825 '#attributes' => array('class' => array('video-bypass-auto-conversion')),
828 elseif (variable_get('video_bypass_conversion', FALSE
)) {
829 $element['bypass_autoconversion'] = array(
831 '#value' => variable_get('video_bypass_conversion', FALSE
),
834 // check this to convert the video on save
835 if (user_access('convert on submission')) {
836 $element['convert_video_on_save'] = array(
837 '#type' => 'checkbox',
838 '#title' => t('Convert video on save'),
839 '#default_value' => variable_get('video_convert_on_save', FALSE
),
840 '#description' => t('This will convert your video on save, instead of scheduling it for cron.'),
841 '#attributes' => array('class' => array('video-convert-video-on-save')),
844 elseif (variable_get('video_convert_on_save', FALSE
)) {
845 $element['convert_video_on_save'] = array(
847 '#value' => variable_get('video_convert_on_save', FALSE
),
852 // use of default thumbnail
853 if (!empty($field['settings']['default_video_thumbnail']['fid'])) {
854 $defaultfid = $field['settings']['default_video_thumbnail']['fid'];
856 $default_thumb = (isset($file['thumbnail']) && $defaultfid == $file['thumbnail']) || variable_get('video_use_default_thumb', FALSE
);
857 if (user_access('use default thumb')) {
858 $element['use_default_video_thumb'] = array(
859 '#type' => 'checkbox',
860 '#title' => t('Use the default thumbnail for this video'),
861 '#default_value' => $default_thumb,
862 '#description' => t('This will set a flag for this video to use the default video thumbnail when output.'),
863 '#attributes' => array('class' => array('video-use-default-video-thumb')),
865 if ($default_thumb) {
866 $element['use_default_video_thumb']['#attributes']['checked'] = 'checked';
870 $element['use_default_video_thumb'] = array(
872 '#value' => $default_thumb,
879 * Updates options list to show matching aspect ratios and matching resolutions
881 * We will update the options array by reference and return the aspect ratio of
884 function _video_dimensions_options(&$options, $video) {
885 $aspect_ratio = _video_aspect_ratio($video);
887 if (empty($aspect_ratio)) {
888 return $aspect_ratio;
891 // Loop through our options and find matching ratio's and also the exact width/height
892 foreach ($options as
$key => $value) {
893 $wxh = explode('x', $value);
894 // Lets check our width and height first
895 if ($aspect_ratio['width'] == $wxh[0] && $aspect_ratio['height'] == $wxh[1]) {
896 $options[$key] = $value .
' (' .
t('Matches resolution of original file') .
')';
899 // Now lets check our ratio's
900 $ratio = number_format($wxh[0] / $wxh[1], 4);
901 if ($ratio == $aspect_ratio['ratio']) {
902 $options[$key] = $value .
' (' .
t('Matches ratio of original file') .
')';
907 return $aspect_ratio;
911 * Returns the width/height and aspect ratio of the video
913 function _video_aspect_ratio($video) {
914 $transcoder = new
Transcoder();
915 $transcoder = $transcoder->getTranscoder();
916 $transcoder->setInput((array) $video);
917 $wxh = $transcoder->getDimensions();
919 if (empty($wxh) || empty($wxh['width']) || empty($wxh['height'])) {
920 // No width and height found. This may be because the transcoder does not support retrieving dimensions.
925 'width' => $wxh['width'],
926 'height' => $wxh['height'],
927 'ratio' => number_format($wxh['width'] / $wxh['height'], 4),
936 * Implements hook_field_formatter_info().
938 function video_field_formatter_info() {
940 'video_formatter_player' => array(
941 'label' => t('Video player'),
942 'field types' => array('video'),
944 'widthxheight' => '640x360',
945 'poster_image_style' => '',
948 'video_formatter_thumbnail' => array(
949 'label' => t('Video thumbnail'),
950 'field types' => array('video'),
960 * Implements hook_field_formatter_settings_form().
962 function video_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
963 $display = $instance['display'][$view_mode];
964 $settings = $display['settings'];
965 $image_styles = image_style_options(FALSE
);
967 switch ($display['type']) {
968 case
'video_formatter_thumbnail':
969 $element['image_style'] = array(
970 '#title' => t('Video thumbnail style'),
972 '#default_value' => $settings['image_style'],
973 '#empty_option' => t('None (original video thumbnail)'),
974 '#options' => $image_styles,
977 $element['image_link'] = array(
978 '#title' => t('Link video or video thumbnail to'),
980 '#default_value' => $settings['image_link'],
981 '#empty_option' => t('Nothing'),
983 'content' => t('Content'),
989 case
'video_formatter_player':
990 $element['widthxheight'] = array(
991 '#title' => t('Dimensions'),
993 '#default_value' => $settings['widthxheight'],
994 '#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'))),
995 '#options' => video_utility
::getDimensions(),
998 $element['poster_image_style'] = array(
999 '#title' => t('Poster image style'),
1000 '#type' => 'select',
1001 '#default_value' => $settings['poster_image_style'],
1002 '#empty_option' => t('None (original image)'),
1003 '#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'))),
1004 '#options' => $image_styles,
1013 * Implements hook_field_formatter_settings_summary().
1015 function video_field_formatter_settings_summary($field, $instance, $view_mode) {
1016 $display = $instance['display'][$view_mode];
1017 $settings = $display['settings'];
1019 $image_styles = image_style_options(FALSE
);
1020 // Unset possible 'No defined styles' option.
1021 unset($image_styles['']);
1023 // Styles could be lost because of enabled/disabled modules that defines
1024 // their styles in code.
1025 switch ($display['type']) {
1026 case
'video_formatter_thumbnail':
1027 if (isset($image_styles[$settings['image_style']])) {
1028 $summary[] = t('Video thumbnail style: @style', array('@style' => $image_styles[$settings['image_style']]));
1031 $summary[] = t('Original video thumbnail');
1034 $link_types = array(
1035 'content' => t('Linked to content'),
1036 'file' => t('Linked to video file'),
1038 // Display this setting only if image is linked.
1039 if (isset($link_types[$settings['image_link']])) {
1040 $summary[] = $link_types[$settings['image_link']];
1044 case
'video_formatter_player':
1045 $summary[] = t('Player dimensions: @widthxheight', array('@widthxheight' => $settings['widthxheight']));
1046 if (isset($image_styles[$settings['poster_image_style']])) {
1047 $summary[] = t('Poster image style: @style', array('@style' => $image_styles[$settings['poster_image_style']]));
1052 return implode('<br />', $summary);
1056 * Implements hook_field_formatter_view().
1058 function video_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1060 $settings = $display['settings'];
1062 foreach ($items as
$delta => $item) {
1063 switch ($display['type']) {
1064 case
'video_formatter_thumbnail':
1065 // Check if the formatter involves a link.
1066 if ($settings['image_link'] == 'content') {
1067 $uri = entity_uri($entity_type, $entity);
1069 elseif ($settings['image_link'] == 'file') {
1072 if (isset($link_file)) {
1074 'path' => file_create_url($item['uri']),
1075 'options' => array(),
1078 $element[$delta] = array(
1079 '#theme' => 'video_formatter_thumbnail',
1081 '#image_style' => $settings['image_style'],
1082 '#path' => isset($uri) ?
$uri : '',
1083 '#entity' => $entity,
1084 '#entity_type' => $entity_type,
1086 '#instance' => $instance
1090 case
'video_formatter_player':
1091 $element[$delta] = array(
1092 '#theme' => 'video_formatter_player',
1094 '#entity' => $entity,
1095 '#entity_type' => $entity_type,
1097 '#instance' => $instance,
1098 '#player_dimensions' => $settings['widthxheight'],
1099 '#poster_image_style' => $settings['poster_image_style'],
1109 * Implements hook_filefield_sources_widgets().
1111 function video_filefield_sources_widgets() {
1112 return array('video_upload');
1116 * Video file save to the video_queue table for conversions
1118 function _video_field_file_autoconversion($entity_type, $entity, $field, $instance, $langcode, &$items) {
1119 $transcoder = new
Transcoder();
1121 if (empty($field['settings']['autoconversion']) || !$transcoder->hasTranscoder()) {
1125 foreach ($items as
$delta => &$item) {
1126 $fid = intval($item['fid']);
1127 // skip adding entry if bypass conversion is checked
1128 if (!empty($item['bypass_autoconversion'])) {
1129 // delete the conversion job if any
1130 video_jobs
::delete($fid);
1134 // Try to load the job
1135 $video = video_jobs
::load($fid);
1137 // Create the job if it doesn't exist
1139 list($entity_id, $entity_vid, $bundle) = entity_extract_ids($entity_type, $entity);
1140 // @todo get the default dimension when not available in $item
1141 if (!video_jobs
::create($item['fid'], $item['dimensions'], $entity_id, $entity_type, $field['field_name'], $langcode, $delta)) {
1142 drupal_set_message(t('Something went wrong with your video job creation. Please check your recent log entries for further debugging.'), 'error');
1145 // Load a fresh copy of the job
1146 $video = video_jobs
::load($fid);
1149 // re queue for video conversion
1150 if (!empty($item['re_convert_video'])) {
1151 $video->video_status
= VIDEO_RENDERING_PENDING
;
1152 $video->statusupdated
= time();
1153 $video->dimensions
= $item['dimensions'];
1154 video_jobs
::update($video);
1157 if ($video->video_status
== VIDEO_RENDERING_PENDING
) {
1158 // Convert on save if the job is pending and if it is requested
1159 // The automatic conversions of files is handled in _video_field_convert_on_save(),
1160 // which is called from hook_entity_insert/hook_entity_update.
1161 if (!empty($item['convert_video_on_save'])) {
1162 // Only save the fid, because the location of the file may change
1163 // between now and _video_field_convert_on_save().
1164 $entity->video_convert_on_save
[$video->fid
] = $video->fid
;
1167 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
)));
1174 * Processes video fields that should convert on save.
1176 * This is not performed in _video_field_file_autoconversion() because
1177 * of incompatibilities with Rules and File(field) Paths.
1179 * When hook_entity_insert/update are called, all field related operations
1180 * are complete and the entity is fully saved to the database. This
1181 * allows Rules to supply a proper entity to the event handlers.
1183 * The $entity->video_convert_on_save property is set in
1184 * _video_field_file_autoconversion().
1186 function _video_field_convert_on_save($entity, $type) {
1187 if (!empty($entity->video_convert_on_save
)) {
1188 $transcoder = new
Transcoder();
1189 $transcodername = $transcoder->getTranscoder()->getName();
1191 foreach ($entity->video_convert_on_save as
$videofid) {
1192 $video = video_jobs
::load($videofid);
1193 if ($transcoder->executeConversion($video)) {
1194 if ($video->video_status
== VIDEO_RENDERING_COMPLETE
) {
1195 drupal_set_message(t('The video %video-name was converted.', array('%video-name' => $video->filename
)));
1198 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
)));
1202 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');
1206 unset($entity->video_convert_on_save
);
1210 function _video_field_get_all_thumbnails(array $field, array $items, $usage_entity_type = NULL
, $usage_entity_id = NULL
) {
1211 if (empty($items)) {
1215 $defaultthumbnailfid = !empty($field['settings']['default_video_thumbnail']) ?
$field['settings']['default_video_thumbnail']['fid'] : 0;
1216 $videofids = array();
1217 $thumbnailfids = array();
1218 foreach ($items as
$item) {
1219 if (!empty($item['fid'])) {
1220 $videofids[] = intval($item['fid']);
1222 // Add the selected thumbnail if it is not the default thumbnail for the field
1223 if (!empty($item['thumbnail']) && $item['thumbnail'] != $defaultthumbnailfid) {
1224 $thumbnailfids[] = intval($item['thumbnail']);
1229 if (empty($videofids)) {
1233 // Add the automatically extracted thumbnails
1234 $query = db_select('video_thumbnails', 't')
1235 ->fields('t', array('thumbnailfid'))
1236 ->condition('videofid', $videofids, 'IN');
1238 // Only return files with usage when requested
1239 if ($usage_entity_type != NULL
&& $usage_entity_id != NULL
) {
1240 $query->innerJoin('file_usage', 'u', 'u.fid = t.thumbnailfid AND u.type = :type AND u.id = :id', array(
1241 ':type' => $usage_entity_type,
1242 ':id' => $usage_entity_id,
1246 $thumbnailfids = array_merge($thumbnailfids, $query->execute()->fetchCol(0));
1248 return video_utility
::objectToArray(file_load_multiple($thumbnailfids));
1251 function _video_field_get_all_converted(array $items, $usage_entity_type = NULL
, $usage_entity_id = NULL
) {
1252 if (empty($items)) {
1256 $videofids = array();
1257 foreach ($items as
$item) {
1258 if (!empty($item['fid'])) {
1259 $videofids[] = intval($item['fid']);
1263 if (empty($videofids)) {
1267 $query = db_select('video_output', 't')
1268 ->fields('t', array('output_fid'))
1269 ->condition('original_fid', $videofids, 'IN');
1271 // Only return files with usage when requested
1272 if ($usage_entity_type != NULL
&& $usage_entity_id != NULL
) {
1273 $query->innerJoin('file_usage', 'u', 'u.fid = t.output_fid AND u.type = :type AND u.id = :id', array(
1274 ':type' => $usage_entity_type,
1275 ':id' => $usage_entity_id,
1279 $convertedfids = $query->execute()->fetchCol(0);
1281 return video_utility
::objectToArray(file_load_multiple($convertedfids));