encode.pl 24 KB

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