encode.pl 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Default configuration
  8. my $FORMAT = 'mp4';
  9. my $AUDIO_BITRATE = 192;
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 22;
  12. my $AUDIO_COPY = 0;
  13. my $STEREO_ONLY = 0;
  14. my $HEIGHT = undef();
  15. my $WIDTH = undef();
  16. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b';
  17. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  18. my $FORCE_MP4 = 0;
  19. # Applicaton configuration
  20. my $HD_WIDTH = 1350;
  21. my $MIN_VIDEO_WIDTH = 100;
  22. my $MAX_CROP_DIFF = .1;
  23. my $MAX_DURA_DIFF = 5;
  24. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', 'AAC', 'OTHER');
  25. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  26. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  27. my $DEBUG = 0;
  28. # General parameters for HandBrake
  29. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  30. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3', '--mixdown', 'dpl2');
  31. # Runtime debug mode
  32. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  33. $DEBUG = 1;
  34. }
  35. # Shortcut config
  36. if ($ENV{'MOBILE'}) {
  37. $ENV{'QUALITY'} = 25;
  38. $ENV{'HEIGHT'} = 720;
  39. $ENV{'WIDTH'} = 1280;
  40. $ENV{'AUDIO_BITRATE'} = 128;
  41. $ENV{'STEREO_ONLY'} = 1;
  42. $ENV{'FORCE_MP4'} = 1;
  43. }
  44. # Additional arguments for HandBrake
  45. # Split on spaces; if you need spaces you'll have to work out something else
  46. if ($ENV{'HANDBRAKE_ARGS'}) {
  47. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  48. push(@video_params, @args);
  49. }
  50. # Allow overrides for audio languages
  51. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  52. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  53. }
  54. # Allow overrides for subtitle languages
  55. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  56. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  57. }
  58. # Allow copy-only audio transfers (for use in re-encoding)
  59. if ($ENV{'AUDIO_COPY'}) {
  60. $AUDIO_COPY = 1;
  61. }
  62. # Allow AAC-only audio transfers (for use in mobile encoding)
  63. if ($ENV{'STEREO_ONLY'}) {
  64. $STEREO_ONLY = 1;
  65. }
  66. # Allow MP4-only output format (for use in mobile encoding)
  67. if ($ENV{'FORCE_MP4'}) {
  68. $FORCE_MP4 = 1;
  69. }
  70. # Allow overrides for video quality
  71. if ($ENV{'QUALITY'}) {
  72. $QUALITY = $ENV{'QUALITY'};
  73. $HD_QUALITY = $ENV{'QUALITY'};
  74. }
  75. # Allow overrides for audio bitrate
  76. if ($ENV{'AUDIO_BITRATE'}) {
  77. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  78. }
  79. # Allow overrides for video height and width. The default is "same as source".
  80. if ($ENV{'HEIGHT'}) {
  81. $HEIGHT = $ENV{'HEIGHT'};
  82. }
  83. if ($ENV{'WIDTH'}) {
  84. $WIDTH = $ENV{'WIDTH'};
  85. }
  86. # Command-line parameters
  87. my ($in_file, $out_file, $title) = @ARGV;
  88. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  89. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  90. }
  91. # Scan for title/track info
  92. my %titles = &scan($in_file);
  93. # Allow external subtitles for single-title files
  94. if (scalar(keys(%titles)) == 1) {
  95. my $srt_file = $in_file;
  96. $srt_file =~ s/\.\w{2,4}$/.srt/;
  97. if (!-r $srt_file) {
  98. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  99. }
  100. if (-r $srt_file) {
  101. if ($DEBUG) {
  102. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  103. }
  104. push(@video_params, '--srt-file', $srt_file);
  105. }
  106. }
  107. # Allow encoding of a specific title
  108. if ($title) {
  109. if ($title =~ /^\d+$/ && $title > 0) {
  110. if (!defined($titles{$title})) {
  111. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  112. }
  113. my $selected_title = $titles{$title};
  114. %titles = ();
  115. $titles{$title} = $selected_title;
  116. } elsif ($title =~ /main/i) {
  117. my $max_title = 0;
  118. my $max_duration = 0;
  119. foreach my $title (keys(%titles)) {
  120. if (!$titles{$title}{'duration'}) {
  121. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  122. next;
  123. }
  124. my $new_max = 0;
  125. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  126. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  127. $new_max = 1;
  128. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  129. $new_max = 1;
  130. }
  131. } elsif ($titles{$title}{'duration'} > $max_duration) {
  132. $new_max = 1;
  133. }
  134. if ($new_max) {
  135. $max_duration = $titles{$title}{'duration'};
  136. $max_title = $title;
  137. }
  138. }
  139. my $selected_title = $titles{$max_title};
  140. %titles = ();
  141. $titles{$max_title} = $selected_title;
  142. }
  143. }
  144. # Ensure we have an output file name
  145. # Force MKV output if the output file name is provided and ends in .MKV
  146. if (!defined($out_file) || length($out_file) < 1) {
  147. $out_file = $in_file;
  148. } else {
  149. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  150. if (defined($force_format) && lc($force_format) eq 'mkv') {
  151. $FORMAT = 'mkv';
  152. }
  153. }
  154. # Keep the original format around so we can reset between tracks
  155. my $FORMAT_ORIG = $FORMAT;
  156. # Encode each title
  157. foreach my $title (keys(%titles)) {
  158. if ($DEBUG) {
  159. print STDERR 'Setting options for title: ' . $title . "\n";
  160. }
  161. # Reset
  162. $FORMAT = $FORMAT_ORIG;
  163. # Parse the title's audio and subtitle tracks
  164. my $scan = $titles{$title};
  165. my @audio = &audioOptions($scan);
  166. my @subs = &subOptions($scan);
  167. # Skip tracks that have no video
  168. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  169. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  170. next;
  171. }
  172. # Skip tracks that have no audio
  173. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  174. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  175. next;
  176. }
  177. # Set the audio quality for re-encoded tracks
  178. push(@audio, '--ab', $AUDIO_BITRATE);
  179. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  180. my $title_quality = $QUALITY;
  181. if ($scan->{'size'}[0] > $HD_WIDTH) {
  182. $title_quality = $HD_QUALITY;
  183. }
  184. # Override unlikely autocrop values
  185. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  186. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  187. {
  188. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  189. my @crop = (0, 0, 0, 0);
  190. $scan->{'crop'} = \@crop;
  191. }
  192. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  193. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  194. if ($track->{'type'} eq 'PGS') {
  195. $FORMAT = 'mkv';
  196. last;
  197. }
  198. }
  199. # Force MKV muxing if the output contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  200. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  201. if ($track->{'codec'} =~ /DTS/i) {
  202. $FORMAT = 'mkv';
  203. last;
  204. }
  205. }
  206. # Select a file name extension that matches the format
  207. my $title_out_file = $out_file;
  208. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  209. if ($FORMAT eq 'mkv') {
  210. $title_out_file .= '.mkv';
  211. } else {
  212. $title_out_file .= '.m4v';
  213. }
  214. # Force the title number into the output file name if there are multiple titles to be encoded
  215. if (scalar(keys(%titles)) > 1) {
  216. my $title_text = sprintf('%02d', $title);
  217. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  218. }
  219. # Limit the maximum height and width, if any is specified
  220. if ($HEIGHT) {
  221. push(@video_params, '--maxHeight', $HEIGHT);
  222. }
  223. if ($WIDTH) {
  224. push(@video_params, '--maxWidth', $WIDTH);
  225. }
  226. # Output file
  227. if (uc($title_out_file) eq uc($in_file)) {
  228. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  229. }
  230. # Build the arugment list
  231. my @args = ($HB_EXEC);
  232. push(@args, '--title', $title);
  233. push(@args, '--input', $in_file);
  234. push(@args, '--output', $title_out_file);
  235. push(@args, '--format', $FORMAT);
  236. push(@args, '--quality', $title_quality);
  237. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  238. push(@args, @video_params);
  239. push(@args, @audio_params);
  240. push(@args, @audio);
  241. push(@args, @subs);
  242. if ($DEBUG) {
  243. print STDERR "\n" . join(' ', @args) . "\n\n";
  244. }
  245. # Sanity check
  246. if (-e $title_out_file) {
  247. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  248. next;
  249. }
  250. # Run it
  251. my $child_out = '';
  252. my $child_in = '';
  253. my $pid = open3($child_in, $child_out, $child_out, @args);
  254. close($child_in);
  255. while (<$child_out>) {
  256. if ($DEBUG) {
  257. print STDERR $_;
  258. }
  259. }
  260. waitpid($pid, 0);
  261. close($child_out);
  262. # Provide the new file name if requested
  263. if ($ENV{'RECODE_OUTFILE'}) {
  264. print $title_out_file;
  265. }
  266. }
  267. # Cleanup
  268. exit(0);
  269. sub subOptions($) {
  270. my ($scan) = @_;
  271. my %tracks = ();
  272. foreach my $track (@{ $scan->{'subtitle'} }) {
  273. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  274. if (!defined($iso)) {
  275. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  276. next;
  277. }
  278. # Map text/bitmap into a boolean
  279. if ($text =~ /TEXT/i) {
  280. $text = 1;
  281. } else {
  282. $text = 0;
  283. }
  284. # Standardize the codes
  285. $iso = uc($iso);
  286. $type = uc($type);
  287. # Push all parsed data into an array
  288. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  289. $tracks{ $track->{'index'} } = \%data;
  290. # Print what we found
  291. if ($DEBUG) {
  292. print STDERR 'Found subtitle track: ';
  293. printHash(\%data);
  294. }
  295. }
  296. # Push the parsed data back up the chain
  297. $scan->{'subtitle_parsed'} = \%tracks;
  298. # Select the subtitle tracks we want to keep
  299. my @keep = ();
  300. foreach my $index (keys(%tracks)) {
  301. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  302. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  303. next;
  304. }
  305. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  306. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  307. push(@keep, $index);
  308. } elsif ($tracks{$index}->{'text'}) {
  309. push(@keep, $index);
  310. } else {
  311. if ($DEBUG) {
  312. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  313. }
  314. }
  315. }
  316. # Push the selected tracks back up the chain
  317. my %tmp = ();
  318. foreach my $num (@keep) {
  319. $tmp{$num} = $tracks{$num};
  320. }
  321. $scan->{'subtitle_selected'} = \%tmp;
  322. # Send back the argument string (if any)
  323. if (scalar(@keep) < 1) {
  324. return '';
  325. }
  326. return ('--subtitle', join(',', @keep));
  327. }
  328. sub audioOptions($) {
  329. my ($scan) = @_;
  330. # Type the audio tracks
  331. my %tracks = ();
  332. foreach my $track (@{ $scan->{'audio'} }) {
  333. my ($language, $codec, $note, $channels, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?/;
  334. if (!defined($channels)) {
  335. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  336. next;
  337. }
  338. # Decode the channels string to a number
  339. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  340. $channels = $1;
  341. } elsif ($channels =~ /Dolby\s+Surround/i) {
  342. $channels = 3.1;
  343. }
  344. # Standardize the codec
  345. foreach my $code (@CODEC_ORDER) {
  346. my $metacode = quotemeta($code);
  347. if ($codec =~ /${metacode}/i) {
  348. $codec = $code;
  349. last;
  350. } elsif ($code eq 'OTHER') {
  351. if ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  352. $codec = $code;
  353. } elsif ($codec eq 'truehd' || $codec eq 'dca') {
  354. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  355. $codec = undef();
  356. } else {
  357. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  358. $codec = $code;
  359. }
  360. }
  361. }
  362. # Push all parsed data into the array
  363. my %data = ('language' => $language, 'codec' => $codec, 'channels' => $channels, 'iso' => $iso, 'note' => $note);
  364. $tracks{ $track->{'index'} } = \%data;
  365. # Print what we found
  366. if ($DEBUG) {
  367. print STDERR 'Found audio track: ';
  368. printHash(\%data);
  369. }
  370. }
  371. # Push the parsed data back up the chain
  372. $scan->{'audio_parsed'} = \%tracks;
  373. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  374. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  375. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  376. my $mixdown = undef();
  377. my %bestByCodec = ();
  378. my $bestCodec = undef();
  379. my $mostChannels = 0;
  380. foreach my $codec (@CODEC_ORDER) {
  381. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  382. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  383. $bestCodec = $codec;
  384. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  385. }
  386. }
  387. foreach my $codec (@CODEC_ORDER) {
  388. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  389. $mixdown = $bestByCodec{$codec};
  390. last;
  391. }
  392. }
  393. # Sanity check
  394. if (!defined($mixdown) || $mixdown < 1) {
  395. print STDERR basename($0) . ": No usable audio tracks in title\n";
  396. return;
  397. }
  398. # Clear the mixdown selection if we're copying audio
  399. if ($AUDIO_COPY) {
  400. $mixdown = undef();
  401. }
  402. # Mixdown track first
  403. my @audio_tracks = ();
  404. if (defined($mixdown) && $mixdown > 0) {
  405. if ($DEBUG) {
  406. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  407. if ($tracks{$mixdown}->{'channels'} > 2) {
  408. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  409. }
  410. }
  411. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  412. push(@audio_tracks, \%track);
  413. }
  414. # Keep all other audio tracks, unless STEREO_ONLY is set
  415. if (!$STEREO_ONLY) {
  416. # Passthru DTS-MA, DTS, AC3, and AAC
  417. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  418. foreach my $index (keys(%tracks)) {
  419. if ($mixdown == $index && $tracks{$index}->{'codec'} eq 'OTHER' && $tracks{$index}->{'channels'} <= 2) {
  420. if ($DEBUG) {
  421. print STDERR 'Skipping recode of track ' . $index . ' since it is already used as the default track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  422. }
  423. next;
  424. } elsif (!$tracks{$index}->{'codec'}) {
  425. if ($DEBUG) {
  426. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  427. }
  428. next;
  429. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  430. if ($DEBUG) {
  431. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  432. }
  433. next;
  434. } else {
  435. my %track = ('index' => $index, 'encoder' => 'copy');
  436. push(@audio_tracks, \%track);
  437. }
  438. }
  439. }
  440. # Push the selected tracks back up the chain
  441. my %tmp = ();
  442. foreach my $track (@audio_tracks) {
  443. $tmp{ $track->{'index'} } = $track;
  444. }
  445. $scan->{'audio_selected'} = \%tmp;
  446. # Consolidate from the hashes
  447. my @output_tracks = ();
  448. my @output_encoders = ();
  449. foreach my $track (@audio_tracks) {
  450. push(@output_tracks, $track->{'index'});
  451. push(@output_encoders, $track->{'encoder'});
  452. }
  453. # Send back the argument strings
  454. return ('--audio', join(',', @output_tracks), '--aencoder', join(',', @output_encoders));
  455. }
  456. sub scan($) {
  457. my ($in_file) = @_;
  458. # Fork to scan the file
  459. my $child_out = '';
  460. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  461. # Loop through the output
  462. my $scan;
  463. my %titles = ();
  464. my $inTitle = 0;
  465. my $zone = '';
  466. while (<$child_out>) {
  467. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  468. if ($DEBUG) {
  469. print STDERR 'Found ' . $1 . " titles in source\n";
  470. }
  471. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  472. my $stream = $1;
  473. my $desc = $2;
  474. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  475. # Save the current title (if any)
  476. if ($inTitle) {
  477. $titles{$inTitle} = $scan;
  478. }
  479. # Grab the new title number
  480. $inTitle = $1;
  481. # Init the data collectors
  482. my @audio = ();
  483. my @crop = ();
  484. my @subtitle = ();
  485. my @size = ();
  486. my %tmp = (
  487. 'audio' => \@audio,
  488. 'crop' => \@crop,
  489. 'subtitle' => \@subtitle,
  490. 'size' => \@size,
  491. 'duration' => 0,
  492. 'aspect' => 0
  493. );
  494. $scan = \%tmp;
  495. if ($DEBUG) {
  496. print STDERR 'Found data for title ' . $1 . "\n";
  497. }
  498. } elsif ($inTitle) {
  499. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  500. push(@{ $scan->{'size'} }, $1, $2);
  501. if ($DEBUG) {
  502. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  503. }
  504. if (/\s+display aspect\: (\d*\.\d+)/) {
  505. $scan->{'aspect'} = $1;
  506. if ($DEBUG) {
  507. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  508. }
  509. }
  510. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  511. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  512. if ($DEBUG) {
  513. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  514. }
  515. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  516. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  517. if ($DEBUG) {
  518. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  519. }
  520. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  521. $zone = 'audio';
  522. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  523. my %track = ('index' => $1, 'description' => $2);
  524. push(@{ $scan->{'audio'} }, \%track);
  525. if ($DEBUG) {
  526. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  527. }
  528. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  529. $zone = 'subtitle';
  530. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  531. my %track = ('index' => $1, 'description' => $2);
  532. push(@{ $scan->{'subtitle'} }, \%track);
  533. if ($DEBUG) {
  534. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  535. }
  536. }
  537. }
  538. }
  539. # Save the last title (if any)
  540. if ($inTitle) {
  541. $titles{$inTitle} = $scan;
  542. }
  543. # Cleanup the scan process
  544. waitpid($pid, 0);
  545. close($child_out);
  546. # Sanity check
  547. if (scalar(keys(%titles)) < 1) {
  548. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  549. }
  550. # Return
  551. return %titles;
  552. }
  553. sub findBestAudioTrack($$) {
  554. my ($tracks, $codec) = @_;
  555. my $best = undef();
  556. my $channels = 0;
  557. for my $index (keys(%{$tracks})) {
  558. my $track = $tracks->{$index};
  559. # Skip tracks not in the specified codec
  560. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  561. next;
  562. }
  563. # Skip foreign language tracks
  564. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  565. next;
  566. }
  567. # Find the track with the most channels (Ófirst wins)
  568. if (!defined($best) || $track->{'channels'} > $channels) {
  569. $best = $index;
  570. $channels = $track->{'channels'};
  571. }
  572. }
  573. return $best;
  574. }
  575. sub isValidSubLanguage($) {
  576. my ($lang, $iso) = @_;
  577. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  578. return 1;
  579. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  580. return 1;
  581. }
  582. return 0;
  583. }
  584. sub isValidAudioLanguage($) {
  585. my ($lang, $iso) = @_;
  586. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  587. return 1;
  588. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  589. return 0;
  590. }
  591. return 1;
  592. }
  593. sub printHash($) {
  594. my ($data) = @_;
  595. my $first = 1;
  596. foreach my $key (keys(%{$data})) {
  597. if (defined($data->{$key})) {
  598. if ($first) {
  599. $first = 0;
  600. } else {
  601. print STDERR ', ';
  602. }
  603. print STDERR $key . ' => ' . $data->{$key};
  604. }
  605. }
  606. print STDERR "\n";
  607. }