movenchint.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  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 "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "internal.h"
  24. #include "rtpenc_chain.h"
  25. #include "avio_internal.h"
  26. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  27. {
  28. MOVMuxContext *mov = s->priv_data;
  29. MOVTrack *track = &mov->tracks[index];
  30. MOVTrack *src_track = &mov->tracks[src_index];
  31. AVStream *src_st = s->streams[src_index];
  32. int ret = AVERROR(ENOMEM);
  33. track->tag = MKTAG('r','t','p',' ');
  34. track->src_track = src_index;
  35. track->enc = avcodec_alloc_context3(NULL);
  36. if (!track->enc)
  37. goto fail;
  38. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  39. track->enc->codec_tag = track->tag;
  40. track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
  41. RTP_MAX_PACKET_SIZE);
  42. if (!track->rtp_ctx)
  43. goto fail;
  44. /* Copy the RTP AVStream timebase back to the hint AVStream */
  45. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  46. /* Mark the hinted track that packets written to it should be
  47. * sent to this track for hinting. */
  48. src_track->hint_track = index;
  49. return 0;
  50. fail:
  51. av_log(s, AV_LOG_WARNING,
  52. "Unable to initialize hinting of stream %d\n", src_index);
  53. av_freep(&track->enc);
  54. /* Set a default timescale, to avoid crashes in av_dump_format */
  55. track->timescale = 90000;
  56. return ret;
  57. }
  58. /**
  59. * Remove the first sample from the sample queue.
  60. */
  61. static void sample_queue_pop(HintSampleQueue *queue)
  62. {
  63. if (queue->len <= 0)
  64. return;
  65. if (queue->samples[0].own_data)
  66. av_free(queue->samples[0].data);
  67. queue->len--;
  68. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  69. }
  70. /**
  71. * Empty the sample queue, releasing all memory.
  72. */
  73. static void sample_queue_free(HintSampleQueue *queue)
  74. {
  75. int i;
  76. for (i = 0; i < queue->len; i++)
  77. if (queue->samples[i].own_data)
  78. av_free(queue->samples[i].data);
  79. av_freep(&queue->samples);
  80. queue->len = 0;
  81. queue->size = 0;
  82. }
  83. /**
  84. * Add a reference to the sample data to the sample queue. The data is
  85. * not copied. sample_queue_retain should be called before pkt->data
  86. * is reused/freed.
  87. */
  88. static void sample_queue_push(HintSampleQueue *queue, uint8_t *data, int size,
  89. int sample)
  90. {
  91. /* No need to keep track of smaller samples, since describing them
  92. * with immediates is more efficient. */
  93. if (size <= 14)
  94. return;
  95. if (!queue->samples || queue->len >= queue->size) {
  96. HintSample* samples;
  97. queue->size += 10;
  98. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  99. if (!samples)
  100. return;
  101. queue->samples = samples;
  102. }
  103. queue->samples[queue->len].data = data;
  104. queue->samples[queue->len].size = size;
  105. queue->samples[queue->len].sample_number = sample;
  106. queue->samples[queue->len].offset = 0;
  107. queue->samples[queue->len].own_data = 0;
  108. queue->len++;
  109. }
  110. /**
  111. * Make local copies of all referenced sample data in the queue.
  112. */
  113. static void sample_queue_retain(HintSampleQueue *queue)
  114. {
  115. int i;
  116. for (i = 0; i < queue->len; ) {
  117. HintSample *sample = &queue->samples[i];
  118. if (!sample->own_data) {
  119. uint8_t* ptr = av_malloc(sample->size);
  120. if (!ptr) {
  121. /* Unable to allocate memory for this one, remove it */
  122. memmove(queue->samples + i, queue->samples + i + 1,
  123. sizeof(HintSample)*(queue->len - i - 1));
  124. queue->len--;
  125. continue;
  126. }
  127. memcpy(ptr, sample->data, sample->size);
  128. sample->data = ptr;
  129. sample->own_data = 1;
  130. }
  131. i++;
  132. }
  133. }
  134. /**
  135. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  136. * large match is found, matching bytes before n_pos are included
  137. * in the match, too (within the limits of the arrays).
  138. *
  139. * @param haystack buffer that may contain parts of needle
  140. * @param h_len length of the haystack buffer
  141. * @param needle buffer containing source data that have been used to
  142. * construct haystack
  143. * @param n_pos start position in needle used for looking for matches
  144. * @param n_len length of the needle buffer
  145. * @param match_h_offset_ptr offset of the first matching byte within haystack
  146. * @param match_n_offset_ptr offset of the first matching byte within needle
  147. * @param match_len_ptr length of the matched segment
  148. * @return 0 if a match was found, < 0 if no match was found
  149. */
  150. static int match_segments(const uint8_t *haystack, int h_len,
  151. const uint8_t *needle, int n_pos, int n_len,
  152. int *match_h_offset_ptr, int *match_n_offset_ptr,
  153. int *match_len_ptr)
  154. {
  155. int h_pos;
  156. for (h_pos = 0; h_pos < h_len; h_pos++) {
  157. int match_len = 0;
  158. int match_h_pos, match_n_pos;
  159. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  160. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  161. needle[n_pos + match_len] == haystack[h_pos + match_len])
  162. match_len++;
  163. if (match_len <= 8)
  164. continue;
  165. /* If a sufficiently large match was found, try to expand
  166. * the matched segment backwards. */
  167. match_h_pos = h_pos;
  168. match_n_pos = n_pos;
  169. while (match_n_pos > 0 && match_h_pos > 0 &&
  170. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  171. match_n_pos--;
  172. match_h_pos--;
  173. match_len++;
  174. }
  175. if (match_len <= 14)
  176. continue;
  177. *match_h_offset_ptr = match_h_pos;
  178. *match_n_offset_ptr = match_n_pos;
  179. *match_len_ptr = match_len;
  180. return 0;
  181. }
  182. return -1;
  183. }
  184. /**
  185. * Look for segments in samples in the sample queue matching the data
  186. * in ptr. Samples not matching are removed from the queue. If a match
  187. * is found, the next time it will look for matches starting from the
  188. * end of the previous matched segment.
  189. *
  190. * @param data data to find matches for in the sample queue
  191. * @param len length of the data buffer
  192. * @param queue samples used for looking for matching segments
  193. * @param pos the offset in data of the matched segment
  194. * @param match_sample the number of the sample that contained the match
  195. * @param match_offset the offset of the matched segment within the sample
  196. * @param match_len the length of the matched segment
  197. * @return 0 if a match was found, < 0 if no match was found
  198. */
  199. static int find_sample_match(const uint8_t *data, int len,
  200. HintSampleQueue *queue, int *pos,
  201. int *match_sample, int *match_offset,
  202. int *match_len)
  203. {
  204. while (queue->len > 0) {
  205. HintSample *sample = &queue->samples[0];
  206. /* If looking for matches in a new sample, skip the first 5 bytes,
  207. * since they often may be modified/removed in the output packet. */
  208. if (sample->offset == 0 && sample->size > 5)
  209. sample->offset = 5;
  210. if (match_segments(data, len, sample->data, sample->offset,
  211. sample->size, pos, match_offset, match_len) == 0) {
  212. *match_sample = sample->sample_number;
  213. /* Next time, look for matches at this offset, with a little
  214. * margin to this match. */
  215. sample->offset = *match_offset + *match_len + 5;
  216. if (sample->offset + 10 >= sample->size)
  217. sample_queue_pop(queue); /* Not enough useful data left */
  218. return 0;
  219. }
  220. if (sample->offset < 10 && sample->size > 20) {
  221. /* No match found from the start of the sample,
  222. * try from the middle of the sample instead. */
  223. sample->offset = sample->size/2;
  224. } else {
  225. /* No match for this sample, remove it */
  226. sample_queue_pop(queue);
  227. }
  228. }
  229. return -1;
  230. }
  231. static void output_immediate(const uint8_t *data, int size,
  232. AVIOContext *out, int *entries)
  233. {
  234. while (size > 0) {
  235. int len = size;
  236. if (len > 14)
  237. len = 14;
  238. avio_w8(out, 1); /* immediate constructor */
  239. avio_w8(out, len); /* amount of valid data */
  240. avio_write(out, data, len);
  241. data += len;
  242. size -= len;
  243. for (; len < 14; len++)
  244. avio_w8(out, 0);
  245. (*entries)++;
  246. }
  247. }
  248. static void output_match(AVIOContext *out, int match_sample,
  249. int match_offset, int match_len, int *entries)
  250. {
  251. avio_w8(out, 2); /* sample constructor */
  252. avio_w8(out, 0); /* track reference */
  253. avio_wb16(out, match_len);
  254. avio_wb32(out, match_sample);
  255. avio_wb32(out, match_offset);
  256. avio_wb16(out, 1); /* bytes per block */
  257. avio_wb16(out, 1); /* samples per block */
  258. (*entries)++;
  259. }
  260. static void describe_payload(const uint8_t *data, int size,
  261. AVIOContext *out, int *entries,
  262. HintSampleQueue *queue)
  263. {
  264. /* Describe the payload using different constructors */
  265. while (size > 0) {
  266. int match_sample, match_offset, match_len, pos;
  267. if (find_sample_match(data, size, queue, &pos, &match_sample,
  268. &match_offset, &match_len) < 0)
  269. break;
  270. output_immediate(data, pos, out, entries);
  271. data += pos;
  272. size -= pos;
  273. output_match(out, match_sample, match_offset, match_len, entries);
  274. data += match_len;
  275. size -= match_len;
  276. }
  277. output_immediate(data, size, out, entries);
  278. }
  279. /**
  280. * Write an RTP hint (that may contain one or more RTP packets)
  281. * for the packets in data. data contains one or more packets with a
  282. * BE32 size header.
  283. *
  284. * @param out buffer where the hints are written
  285. * @param data buffer containing RTP packets
  286. * @param size the size of the data buffer
  287. * @param trk the MOVTrack for the hint track
  288. * @param pts pointer where the timestamp for the written RTP hint is stored
  289. * @return the number of RTP packets in the written hint
  290. */
  291. static int write_hint_packets(AVIOContext *out, const uint8_t *data,
  292. int size, MOVTrack *trk, int64_t *pts)
  293. {
  294. int64_t curpos;
  295. int64_t count_pos, entries_pos;
  296. int count = 0, entries;
  297. count_pos = avio_tell(out);
  298. /* RTPsample header */
  299. avio_wb16(out, 0); /* packet count */
  300. avio_wb16(out, 0); /* reserved */
  301. while (size > 4) {
  302. uint32_t packet_len = AV_RB32(data);
  303. uint16_t seq;
  304. uint32_t ts;
  305. data += 4;
  306. size -= 4;
  307. if (packet_len > size || packet_len <= 12)
  308. break;
  309. if (data[1] >= 200 && data[1] <= 204) {
  310. /* RTCP packet, just skip */
  311. data += packet_len;
  312. size -= packet_len;
  313. continue;
  314. }
  315. if (packet_len > trk->max_packet_size)
  316. trk->max_packet_size = packet_len;
  317. seq = AV_RB16(&data[2]);
  318. ts = AV_RB32(&data[4]);
  319. if (trk->prev_rtp_ts == 0)
  320. trk->prev_rtp_ts = ts;
  321. /* Unwrap the 32-bit RTP timestamp that wraps around often
  322. * into a not (as often) wrapping 64-bit timestamp. */
  323. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  324. trk->prev_rtp_ts = ts;
  325. if (*pts == AV_NOPTS_VALUE)
  326. *pts = trk->cur_rtp_ts_unwrapped;
  327. count++;
  328. /* RTPpacket header */
  329. avio_wb32(out, 0); /* relative_time */
  330. avio_write(out, data, 2); /* RTP header */
  331. avio_wb16(out, seq); /* RTPsequenceseed */
  332. avio_wb16(out, 0); /* reserved + flags */
  333. entries_pos = avio_tell(out);
  334. avio_wb16(out, 0); /* entry count */
  335. data += 12;
  336. size -= 12;
  337. packet_len -= 12;
  338. entries = 0;
  339. /* Write one or more constructors describing the payload data */
  340. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  341. data += packet_len;
  342. size -= packet_len;
  343. curpos = avio_tell(out);
  344. avio_seek(out, entries_pos, SEEK_SET);
  345. avio_wb16(out, entries);
  346. avio_seek(out, curpos, SEEK_SET);
  347. }
  348. curpos = avio_tell(out);
  349. avio_seek(out, count_pos, SEEK_SET);
  350. avio_wb16(out, count);
  351. avio_seek(out, curpos, SEEK_SET);
  352. return count;
  353. }
  354. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  355. int track_index, int sample,
  356. uint8_t *sample_data, int sample_size)
  357. {
  358. MOVMuxContext *mov = s->priv_data;
  359. MOVTrack *trk = &mov->tracks[track_index];
  360. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  361. uint8_t *buf = NULL;
  362. int size;
  363. AVIOContext *hintbuf = NULL;
  364. AVPacket hint_pkt;
  365. int ret = 0, count;
  366. if (!rtp_ctx)
  367. return AVERROR(ENOENT);
  368. if (!rtp_ctx->pb)
  369. return AVERROR(ENOMEM);
  370. if (sample_data)
  371. sample_queue_push(&trk->sample_queue, sample_data, sample_size, sample);
  372. else
  373. sample_queue_push(&trk->sample_queue, pkt->data, pkt->size, sample);
  374. /* Feed the packet to the RTP muxer */
  375. ff_write_chained(rtp_ctx, 0, pkt, s);
  376. /* Fetch the output from the RTP muxer, open a new output buffer
  377. * for next time. */
  378. size = avio_close_dyn_buf(rtp_ctx->pb, &buf);
  379. if ((ret = ffio_open_dyn_packet_buf(&rtp_ctx->pb,
  380. RTP_MAX_PACKET_SIZE)) < 0)
  381. goto done;
  382. if (size <= 0)
  383. goto done;
  384. /* Open a buffer for writing the hint */
  385. if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)
  386. goto done;
  387. av_init_packet(&hint_pkt);
  388. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  389. av_freep(&buf);
  390. /* Write the hint data into the hint track */
  391. hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);
  392. hint_pkt.data = buf;
  393. hint_pkt.pts = hint_pkt.dts;
  394. hint_pkt.stream_index = track_index;
  395. if (pkt->flags & AV_PKT_FLAG_KEY)
  396. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  397. if (count > 0)
  398. ff_mov_write_packet(s, &hint_pkt);
  399. done:
  400. av_free(buf);
  401. sample_queue_retain(&trk->sample_queue);
  402. return ret;
  403. }
  404. void ff_mov_close_hinting(MOVTrack *track) {
  405. AVFormatContext* rtp_ctx = track->rtp_ctx;
  406. uint8_t *ptr;
  407. av_freep(&track->enc);
  408. sample_queue_free(&track->sample_queue);
  409. if (!rtp_ctx)
  410. return;
  411. if (rtp_ctx->pb) {
  412. av_write_trailer(rtp_ctx);
  413. avio_close_dyn_buf(rtp_ctx->pb, &ptr);
  414. av_free(ptr);
  415. }
  416. avformat_free_context(rtp_ctx);
  417. }