encode.pl 21 KB

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