nutenc.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. /*
  2. * nut muxer
  3. * Copyright (c) 2004-2007 Michael Niedermayer
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/intreadwrite.h"
  22. #include "libavutil/mathematics.h"
  23. #include "libavutil/tree.h"
  24. #include "libavutil/dict.h"
  25. #include "libavcodec/mpegaudiodata.h"
  26. #include "nut.h"
  27. #include "internal.h"
  28. #include "avio_internal.h"
  29. static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
  30. int sample_rate= c->sample_rate;
  31. if(size>4096)
  32. return 0;
  33. AV_WB24(out, 1);
  34. if(c->codec_id == CODEC_ID_MPEG4){
  35. if(key_frame){
  36. return 3;
  37. }else{
  38. out[3]= 0xB6;
  39. return 4;
  40. }
  41. }else if(c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MPEG2VIDEO){
  42. return 3;
  43. }else if(c->codec_id == CODEC_ID_H264){
  44. return 3;
  45. }else if(c->codec_id == CODEC_ID_MP3 || c->codec_id == CODEC_ID_MP2){
  46. int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
  47. int layer= c->codec_id == CODEC_ID_MP3 ? 3 : 2;
  48. unsigned int header= 0xFFF00000;
  49. lsf = sample_rate < (24000+32000)/2;
  50. mpeg25 = sample_rate < (12000+16000)/2;
  51. sample_rate <<= lsf + mpeg25;
  52. if (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
  53. else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
  54. else sample_rate_index=1;
  55. sample_rate= ff_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
  56. for(bitrate_index=2; bitrate_index<30; bitrate_index++){
  57. frame_size = ff_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
  58. frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
  59. if(frame_size == size)
  60. break;
  61. }
  62. header |= (!lsf)<<19;
  63. header |= (4-layer)<<17;
  64. header |= 1<<16; //no crc
  65. AV_WB32(out, header);
  66. if(size <= 0)
  67. return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
  68. if(bitrate_index == 30)
  69. return -1; //something is wrong ...
  70. header |= (bitrate_index>>1)<<12;
  71. header |= sample_rate_index<<10;
  72. header |= (bitrate_index&1)<<9;
  73. return 2; //FIXME actually put the needed ones in build_elision_headers()
  74. return 3; //we guess that the private bit is not set
  75. //FIXME the above assumptions should be checked, if these turn out false too often something should be done
  76. }
  77. return 0;
  78. }
  79. static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
  80. NUTContext *nut = s->priv_data;
  81. uint8_t out[64];
  82. int i;
  83. int len= find_expected_header(c, size, frame_type, out);
  84. //av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
  85. for(i=1; i<nut->header_count; i++){
  86. if( len == nut->header_len[i]
  87. && !memcmp(out, nut->header[i], len)){
  88. // av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
  89. return i;
  90. }
  91. }
  92. // av_log(NULL, AV_LOG_ERROR, "nothing found\n");
  93. return 0;
  94. }
  95. static void build_elision_headers(AVFormatContext *s){
  96. NUTContext *nut = s->priv_data;
  97. int i;
  98. //FIXME this is lame
  99. //FIXME write a 2pass mode to find the maximal headers
  100. static const uint8_t headers[][5]={
  101. {3, 0x00, 0x00, 0x01},
  102. {4, 0x00, 0x00, 0x01, 0xB6},
  103. {2, 0xFF, 0xFA}, //mp3+crc
  104. {2, 0xFF, 0xFB}, //mp3
  105. {2, 0xFF, 0xFC}, //mp2+crc
  106. {2, 0xFF, 0xFD}, //mp2
  107. };
  108. nut->header_count= 7;
  109. for(i=1; i<nut->header_count; i++){
  110. nut->header_len[i]= headers[i-1][0];
  111. nut->header [i]= &headers[i-1][1];
  112. }
  113. }
  114. static void build_frame_code(AVFormatContext *s){
  115. NUTContext *nut = s->priv_data;
  116. int key_frame, index, pred, stream_id;
  117. int start=1;
  118. int end= 254;
  119. int keyframe_0_esc= s->nb_streams > 2;
  120. int pred_table[10];
  121. FrameCode *ft;
  122. ft= &nut->frame_code[start];
  123. ft->flags= FLAG_CODED;
  124. ft->size_mul=1;
  125. ft->pts_delta=1;
  126. start++;
  127. if(keyframe_0_esc){
  128. /* keyframe = 0 escape */
  129. FrameCode *ft= &nut->frame_code[start];
  130. ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
  131. ft->size_mul=1;
  132. start++;
  133. }
  134. for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
  135. int start2= start + (end-start)*stream_id / s->nb_streams;
  136. int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
  137. AVCodecContext *codec = s->streams[stream_id]->codec;
  138. int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
  139. int intra_only= /*codec->intra_only || */is_audio;
  140. int pred_count;
  141. for(key_frame=0; key_frame<2; key_frame++){
  142. if(intra_only && keyframe_0_esc && key_frame==0)
  143. continue;
  144. {
  145. FrameCode *ft= &nut->frame_code[start2];
  146. ft->flags= FLAG_KEY*key_frame;
  147. ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
  148. ft->stream_id= stream_id;
  149. ft->size_mul=1;
  150. if(is_audio)
  151. ft->header_idx= find_header_idx(s, codec, -1, key_frame);
  152. start2++;
  153. }
  154. }
  155. key_frame= intra_only;
  156. #if 1
  157. if(is_audio){
  158. int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
  159. int pts;
  160. for(pts=0; pts<2; pts++){
  161. for(pred=0; pred<2; pred++){
  162. FrameCode *ft= &nut->frame_code[start2];
  163. ft->flags= FLAG_KEY*key_frame;
  164. ft->stream_id= stream_id;
  165. ft->size_mul=frame_bytes + 2;
  166. ft->size_lsb=frame_bytes + pred;
  167. ft->pts_delta=pts;
  168. ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
  169. start2++;
  170. }
  171. }
  172. }else{
  173. FrameCode *ft= &nut->frame_code[start2];
  174. ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
  175. ft->stream_id= stream_id;
  176. ft->size_mul=1;
  177. ft->pts_delta=1;
  178. start2++;
  179. }
  180. #endif
  181. if(codec->has_b_frames){
  182. pred_count=5;
  183. pred_table[0]=-2;
  184. pred_table[1]=-1;
  185. pred_table[2]=1;
  186. pred_table[3]=3;
  187. pred_table[4]=4;
  188. }else if(codec->codec_id == CODEC_ID_VORBIS){
  189. pred_count=3;
  190. pred_table[0]=2;
  191. pred_table[1]=9;
  192. pred_table[2]=16;
  193. }else{
  194. pred_count=1;
  195. pred_table[0]=1;
  196. }
  197. for(pred=0; pred<pred_count; pred++){
  198. int start3= start2 + (end2-start2)*pred / pred_count;
  199. int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
  200. for(index=start3; index<end3; index++){
  201. FrameCode *ft= &nut->frame_code[index];
  202. ft->flags= FLAG_KEY*key_frame;
  203. ft->flags|= FLAG_SIZE_MSB;
  204. ft->stream_id= stream_id;
  205. //FIXME use single byte size and pred from last
  206. ft->size_mul= end3-start3;
  207. ft->size_lsb= index - start3;
  208. ft->pts_delta= pred_table[pred];
  209. if(is_audio)
  210. ft->header_idx= find_header_idx(s, codec, -1, key_frame);
  211. }
  212. }
  213. }
  214. memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
  215. nut->frame_code[ 0].flags=
  216. nut->frame_code[255].flags=
  217. nut->frame_code['N'].flags= FLAG_INVALID;
  218. }
  219. static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
  220. val *= nut->time_base_count;
  221. val += time_base - nut->time_base;
  222. ff_put_v(bc, val);
  223. }
  224. /**
  225. * Store a string as vb.
  226. */
  227. static void put_str(AVIOContext *bc, const char *string){
  228. int len= strlen(string);
  229. ff_put_v(bc, len);
  230. avio_write(bc, string, len);
  231. }
  232. static void put_s(AVIOContext *bc, int64_t val){
  233. ff_put_v(bc, 2*FFABS(val) - (val>0));
  234. }
  235. #ifdef TRACE
  236. static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, char *file, char *func, int line){
  237. av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  238. ff_put_v(bc, v);
  239. }
  240. static inline void put_s_trace(AVIOContext *bc, int64_t v, char *file, char *func, int line){
  241. av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  242. put_s(bc, v);
  243. }
  244. #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  245. #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  246. #endif
  247. //FIXME remove calculate_checksum
  248. static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
  249. uint8_t *dyn_buf=NULL;
  250. int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
  251. int forw_ptr= dyn_size + 4*calculate_checksum;
  252. if(forw_ptr > 4096)
  253. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  254. avio_wb64(bc, startcode);
  255. ff_put_v(bc, forw_ptr);
  256. if(forw_ptr > 4096)
  257. avio_wl32(bc, ffio_get_checksum(bc));
  258. if(calculate_checksum)
  259. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  260. avio_write(bc, dyn_buf, dyn_size);
  261. if(calculate_checksum)
  262. avio_wl32(bc, ffio_get_checksum(bc));
  263. av_free(dyn_buf);
  264. }
  265. static void write_mainheader(NUTContext *nut, AVIOContext *bc){
  266. int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
  267. int64_t tmp_match;
  268. ff_put_v(bc, 3); /* version */
  269. ff_put_v(bc, nut->avf->nb_streams);
  270. ff_put_v(bc, nut->max_distance);
  271. ff_put_v(bc, nut->time_base_count);
  272. for(i=0; i<nut->time_base_count; i++){
  273. ff_put_v(bc, nut->time_base[i].num);
  274. ff_put_v(bc, nut->time_base[i].den);
  275. }
  276. tmp_pts=0;
  277. tmp_mul=1;
  278. tmp_stream=0;
  279. tmp_match= 1-(1LL<<62);
  280. tmp_head_idx= 0;
  281. for(i=0; i<256;){
  282. tmp_fields=0;
  283. tmp_size=0;
  284. // tmp_res=0;
  285. if(tmp_pts != nut->frame_code[i].pts_delta) tmp_fields=1;
  286. if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
  287. if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
  288. if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
  289. // if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
  290. if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
  291. tmp_pts = nut->frame_code[i].pts_delta;
  292. tmp_flags = nut->frame_code[i].flags;
  293. tmp_stream= nut->frame_code[i].stream_id;
  294. tmp_mul = nut->frame_code[i].size_mul;
  295. tmp_size = nut->frame_code[i].size_lsb;
  296. // tmp_res = nut->frame_code[i].res;
  297. tmp_head_idx= nut->frame_code[i].header_idx;
  298. for(j=0; i<256; j++,i++){
  299. if(i == 'N'){
  300. j--;
  301. continue;
  302. }
  303. if(nut->frame_code[i].pts_delta != tmp_pts ) break;
  304. if(nut->frame_code[i].flags != tmp_flags ) break;
  305. if(nut->frame_code[i].stream_id != tmp_stream) break;
  306. if(nut->frame_code[i].size_mul != tmp_mul ) break;
  307. if(nut->frame_code[i].size_lsb != tmp_size+j) break;
  308. // if(nut->frame_code[i].res != tmp_res ) break;
  309. if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
  310. }
  311. if(j != tmp_mul - tmp_size) tmp_fields=6;
  312. ff_put_v(bc, tmp_flags);
  313. ff_put_v(bc, tmp_fields);
  314. if(tmp_fields>0) put_s(bc, tmp_pts);
  315. if(tmp_fields>1) ff_put_v(bc, tmp_mul);
  316. if(tmp_fields>2) ff_put_v(bc, tmp_stream);
  317. if(tmp_fields>3) ff_put_v(bc, tmp_size);
  318. if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
  319. if(tmp_fields>5) ff_put_v(bc, j);
  320. if(tmp_fields>6) ff_put_v(bc, tmp_match);
  321. if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
  322. }
  323. ff_put_v(bc, nut->header_count-1);
  324. for(i=1; i<nut->header_count; i++){
  325. ff_put_v(bc, nut->header_len[i]);
  326. avio_write(bc, nut->header[i], nut->header_len[i]);
  327. }
  328. }
  329. static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
  330. NUTContext *nut = avctx->priv_data;
  331. AVCodecContext *codec = st->codec;
  332. ff_put_v(bc, i);
  333. switch(codec->codec_type){
  334. case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
  335. case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
  336. case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
  337. default : ff_put_v(bc, 3); break;
  338. }
  339. ff_put_v(bc, 4);
  340. if (codec->codec_tag){
  341. avio_wl32(bc, codec->codec_tag);
  342. } else {
  343. av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
  344. return AVERROR(EINVAL);
  345. }
  346. ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
  347. ff_put_v(bc, nut->stream[i].msb_pts_shift);
  348. ff_put_v(bc, nut->stream[i].max_pts_distance);
  349. ff_put_v(bc, codec->has_b_frames);
  350. avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
  351. ff_put_v(bc, codec->extradata_size);
  352. avio_write(bc, codec->extradata, codec->extradata_size);
  353. switch(codec->codec_type){
  354. case AVMEDIA_TYPE_AUDIO:
  355. ff_put_v(bc, codec->sample_rate);
  356. ff_put_v(bc, 1);
  357. ff_put_v(bc, codec->channels);
  358. break;
  359. case AVMEDIA_TYPE_VIDEO:
  360. ff_put_v(bc, codec->width);
  361. ff_put_v(bc, codec->height);
  362. if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
  363. ff_put_v(bc, 0);
  364. ff_put_v(bc, 0);
  365. }else{
  366. ff_put_v(bc, st->sample_aspect_ratio.num);
  367. ff_put_v(bc, st->sample_aspect_ratio.den);
  368. }
  369. ff_put_v(bc, 0); /* csp type -- unknown */
  370. break;
  371. default:
  372. break;
  373. }
  374. return 0;
  375. }
  376. static int add_info(AVIOContext *bc, const char *type, const char *value){
  377. put_str(bc, type);
  378. put_s(bc, -1);
  379. put_str(bc, value);
  380. return 1;
  381. }
  382. static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
  383. AVFormatContext *s= nut->avf;
  384. AVDictionaryEntry *t = NULL;
  385. AVIOContext *dyn_bc;
  386. uint8_t *dyn_buf=NULL;
  387. int count=0, dyn_size;
  388. int ret = avio_open_dyn_buf(&dyn_bc);
  389. if(ret < 0)
  390. return ret;
  391. while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
  392. count += add_info(dyn_bc, t->key, t->value);
  393. ff_put_v(bc, 0); //stream_if_plus1
  394. ff_put_v(bc, 0); //chapter_id
  395. ff_put_v(bc, 0); //timestamp_start
  396. ff_put_v(bc, 0); //length
  397. ff_put_v(bc, count);
  398. dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
  399. avio_write(bc, dyn_buf, dyn_size);
  400. av_free(dyn_buf);
  401. return 0;
  402. }
  403. static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
  404. AVFormatContext *s= nut->avf;
  405. AVStream* st = s->streams[stream_id];
  406. AVIOContext *dyn_bc;
  407. uint8_t *dyn_buf=NULL;
  408. int count=0, dyn_size, i;
  409. int ret = avio_open_dyn_buf(&dyn_bc);
  410. if(ret < 0)
  411. return ret;
  412. for (i=0; ff_nut_dispositions[i].flag; ++i) {
  413. if (st->disposition & ff_nut_dispositions[i].flag)
  414. count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
  415. }
  416. dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
  417. if (count) {
  418. ff_put_v(bc, stream_id + 1); //stream_id_plus1
  419. ff_put_v(bc, 0); //chapter_id
  420. ff_put_v(bc, 0); //timestamp_start
  421. ff_put_v(bc, 0); //length
  422. ff_put_v(bc, count);
  423. avio_write(bc, dyn_buf, dyn_size);
  424. }
  425. av_free(dyn_buf);
  426. return count;
  427. }
  428. static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
  429. {
  430. AVIOContext *dyn_bc;
  431. uint8_t *dyn_buf = NULL;
  432. AVDictionaryEntry *t = NULL;
  433. AVChapter *ch = nut->avf->chapters[id];
  434. int ret, dyn_size, count = 0;
  435. ret = avio_open_dyn_buf(&dyn_bc);
  436. if (ret < 0)
  437. return ret;
  438. ff_put_v(bc, 0); // stream_id_plus1
  439. put_s(bc, id + 1); // chapter_id
  440. put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
  441. ff_put_v(bc, ch->end - ch->start); // chapter_len
  442. while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
  443. count += add_info(dyn_bc, t->key, t->value);
  444. ff_put_v(bc, count);
  445. dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
  446. avio_write(bc, dyn_buf, dyn_size);
  447. av_freep(&dyn_buf);
  448. return 0;
  449. }
  450. static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
  451. NUTContext *nut = avctx->priv_data;
  452. AVIOContext *dyn_bc;
  453. int i, ret;
  454. ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
  455. ret = avio_open_dyn_buf(&dyn_bc);
  456. if(ret < 0)
  457. return ret;
  458. write_mainheader(nut, dyn_bc);
  459. put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
  460. for (i=0; i < nut->avf->nb_streams; i++){
  461. ret = avio_open_dyn_buf(&dyn_bc);
  462. if(ret < 0)
  463. return ret;
  464. if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
  465. return ret;
  466. put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
  467. }
  468. ret = avio_open_dyn_buf(&dyn_bc);
  469. if(ret < 0)
  470. return ret;
  471. write_globalinfo(nut, dyn_bc);
  472. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  473. for (i = 0; i < nut->avf->nb_streams; i++) {
  474. ret = avio_open_dyn_buf(&dyn_bc);
  475. if(ret < 0)
  476. return ret;
  477. ret = write_streaminfo(nut, dyn_bc, i);
  478. if (ret < 0)
  479. return ret;
  480. if (ret > 0)
  481. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  482. else {
  483. uint8_t* buf;
  484. avio_close_dyn_buf(dyn_bc, &buf);
  485. av_free(buf);
  486. }
  487. }
  488. for (i = 0; i < nut->avf->nb_chapters; i++) {
  489. ret = avio_open_dyn_buf(&dyn_bc);
  490. if (ret < 0)
  491. return ret;
  492. ret = write_chapter(nut, dyn_bc, i);
  493. if (ret < 0) {
  494. uint8_t *buf;
  495. avio_close_dyn_buf(dyn_bc, &buf);
  496. av_freep(&buf);
  497. return ret;
  498. }
  499. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  500. }
  501. nut->last_syncpoint_pos= INT_MIN;
  502. nut->header_count++;
  503. return 0;
  504. }
  505. static int write_header(AVFormatContext *s){
  506. NUTContext *nut = s->priv_data;
  507. AVIOContext *bc = s->pb;
  508. int i, j, ret;
  509. nut->avf= s;
  510. nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
  511. nut->chapter = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
  512. nut->time_base= av_mallocz(sizeof(AVRational )*(s->nb_streams +
  513. s->nb_chapters));
  514. if (!nut->stream || !nut->chapter || !nut->time_base) {
  515. av_freep(&nut->stream);
  516. av_freep(&nut->chapter);
  517. av_freep(&nut->time_base);
  518. return AVERROR(ENOMEM);
  519. }
  520. for(i=0; i<s->nb_streams; i++){
  521. AVStream *st= s->streams[i];
  522. int ssize;
  523. AVRational time_base;
  524. ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
  525. av_set_pts_info(st, 64, time_base.num, time_base.den);
  526. for(j=0; j<nut->time_base_count; j++){
  527. if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
  528. break;
  529. }
  530. }
  531. nut->time_base[j]= time_base;
  532. nut->stream[i].time_base= &nut->time_base[j];
  533. if(j==nut->time_base_count)
  534. nut->time_base_count++;
  535. if(INT64_C(1000) * time_base.num >= time_base.den)
  536. nut->stream[i].msb_pts_shift = 7;
  537. else
  538. nut->stream[i].msb_pts_shift = 14;
  539. nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
  540. }
  541. for (i = 0; i < s->nb_chapters; i++) {
  542. AVChapter *ch = s->chapters[i];
  543. for (j = 0; j < nut->time_base_count; j++) {
  544. if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
  545. break;
  546. }
  547. nut->time_base[j] = ch->time_base;
  548. nut->chapter[i].time_base = &nut->time_base[j];
  549. if(j == nut->time_base_count)
  550. nut->time_base_count++;
  551. }
  552. nut->max_distance = MAX_DISTANCE;
  553. build_elision_headers(s);
  554. build_frame_code(s);
  555. assert(nut->frame_code['N'].flags == FLAG_INVALID);
  556. avio_write(bc, ID_STRING, strlen(ID_STRING));
  557. avio_w8(bc, 0);
  558. if ((ret = write_headers(s, bc)) < 0)
  559. return ret;
  560. avio_flush(bc);
  561. //FIXME index
  562. return 0;
  563. }
  564. static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
  565. int flags= 0;
  566. if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
  567. if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
  568. if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
  569. if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
  570. if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
  571. if(FFABS(pkt->pts - nus->last_pts)
  572. > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
  573. if( pkt->size < nut->header_len[fc->header_idx]
  574. || (pkt->size > 4096 && fc->header_idx)
  575. || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
  576. flags |= FLAG_HEADER_IDX;
  577. return flags | (fc->flags & FLAG_CODED);
  578. }
  579. static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
  580. int i;
  581. int best_i = 0;
  582. int best_len= 0;
  583. if(pkt->size > 4096)
  584. return 0;
  585. for(i=1; i<nut->header_count; i++){
  586. if( pkt->size >= nut->header_len[i]
  587. && nut->header_len[i] > best_len
  588. && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
  589. best_i= i;
  590. best_len= nut->header_len[i];
  591. }
  592. }
  593. return best_i;
  594. }
  595. static int write_packet(AVFormatContext *s, AVPacket *pkt){
  596. NUTContext *nut = s->priv_data;
  597. StreamContext *nus= &nut->stream[pkt->stream_index];
  598. AVIOContext *bc = s->pb, *dyn_bc;
  599. FrameCode *fc;
  600. int64_t coded_pts;
  601. int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
  602. int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
  603. int store_sp=0;
  604. int ret;
  605. if(pkt->pts < 0)
  606. return -1;
  607. if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
  608. write_headers(s, bc);
  609. if(key_frame && !(nus->last_flags & FLAG_KEY))
  610. store_sp= 1;
  611. if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
  612. store_sp= 1;
  613. //FIXME: Ensure store_sp is 1 in the first place.
  614. if(store_sp){
  615. Syncpoint *sp, dummy= {.pos= INT64_MAX};
  616. ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
  617. for(i=0; i<s->nb_streams; i++){
  618. AVStream *st= s->streams[i];
  619. int64_t dts_tb = av_rescale_rnd(pkt->dts,
  620. nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
  621. nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
  622. AV_ROUND_DOWN);
  623. int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
  624. if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
  625. }
  626. if(dummy.pos == INT64_MAX)
  627. dummy.pos= 0;
  628. sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
  629. NULL);
  630. nut->last_syncpoint_pos= avio_tell(bc);
  631. ret = avio_open_dyn_buf(&dyn_bc);
  632. if(ret < 0)
  633. return ret;
  634. put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
  635. ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
  636. put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
  637. ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
  638. }
  639. assert(nus->last_pts != AV_NOPTS_VALUE);
  640. coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
  641. if(ff_lsb2full(nus, coded_pts) != pkt->pts)
  642. coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
  643. best_header_idx= find_best_header_idx(nut, pkt);
  644. best_length=INT_MAX;
  645. frame_code= -1;
  646. for(i=0; i<256; i++){
  647. int length= 0;
  648. FrameCode *fc= &nut->frame_code[i];
  649. int flags= fc->flags;
  650. if(flags & FLAG_INVALID)
  651. continue;
  652. needed_flags= get_needed_flags(nut, nus, fc, pkt);
  653. if(flags & FLAG_CODED){
  654. length++;
  655. flags = needed_flags;
  656. }
  657. if((flags & needed_flags) != needed_flags)
  658. continue;
  659. if((flags ^ needed_flags) & FLAG_KEY)
  660. continue;
  661. if(flags & FLAG_STREAM_ID)
  662. length+= ff_get_v_length(pkt->stream_index);
  663. if(pkt->size % fc->size_mul != fc->size_lsb)
  664. continue;
  665. if(flags & FLAG_SIZE_MSB)
  666. length += ff_get_v_length(pkt->size / fc->size_mul);
  667. if(flags & FLAG_CHECKSUM)
  668. length+=4;
  669. if(flags & FLAG_CODED_PTS)
  670. length += ff_get_v_length(coded_pts);
  671. if( (flags & FLAG_CODED)
  672. && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
  673. flags |= FLAG_HEADER_IDX;
  674. }
  675. if(flags & FLAG_HEADER_IDX){
  676. length += 1 - nut->header_len[best_header_idx];
  677. }else{
  678. length -= nut->header_len[fc->header_idx];
  679. }
  680. length*=4;
  681. length+= !(flags & FLAG_CODED_PTS);
  682. length+= !(flags & FLAG_CHECKSUM);
  683. if(length < best_length){
  684. best_length= length;
  685. frame_code=i;
  686. }
  687. }
  688. assert(frame_code != -1);
  689. fc= &nut->frame_code[frame_code];
  690. flags= fc->flags;
  691. needed_flags= get_needed_flags(nut, nus, fc, pkt);
  692. header_idx= fc->header_idx;
  693. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  694. avio_w8(bc, frame_code);
  695. if(flags & FLAG_CODED){
  696. ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
  697. flags = needed_flags;
  698. }
  699. if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
  700. if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
  701. if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul);
  702. if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
  703. if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
  704. else ffio_get_checksum(bc);
  705. avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
  706. nus->last_flags= flags;
  707. nus->last_pts= pkt->pts;
  708. //FIXME just store one per syncpoint
  709. if(flags & FLAG_KEY)
  710. av_add_index_entry(
  711. s->streams[pkt->stream_index],
  712. nut->last_syncpoint_pos,
  713. pkt->pts,
  714. 0,
  715. 0,
  716. AVINDEX_KEYFRAME);
  717. return 0;
  718. }
  719. static int write_trailer(AVFormatContext *s){
  720. NUTContext *nut= s->priv_data;
  721. AVIOContext *bc= s->pb;
  722. while(nut->header_count<3)
  723. write_headers(s, bc);
  724. avio_flush(bc);
  725. ff_nut_free_sp(nut);
  726. av_freep(&nut->stream);
  727. av_freep(&nut->chapter);
  728. av_freep(&nut->time_base);
  729. return 0;
  730. }
  731. AVOutputFormat ff_nut_muxer = {
  732. .name = "nut",
  733. .long_name = NULL_IF_CONFIG_SMALL("NUT format"),
  734. .mime_type = "video/x-nut",
  735. .extensions = "nut",
  736. .priv_data_size = sizeof(NUTContext),
  737. #if CONFIG_LIBVORBIS
  738. .audio_codec = CODEC_ID_VORBIS,
  739. #elif CONFIG_LIBMP3LAME
  740. .audio_codec = CODEC_ID_MP3,
  741. #else
  742. .audio_codec = CODEC_ID_MP2,
  743. #endif
  744. .video_codec = CODEC_ID_MPEG4,
  745. .write_header = write_header,
  746. .write_packet = write_packet,
  747. .write_trailer = write_trailer,
  748. .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
  749. .codec_tag = (const AVCodecTag * const []){ ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
  750. };